leetcode -- 412、414

412. Fizz Buzz

Problem Description

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,
Return:
[
“1”,
“2”,
“Fizz”,
“4”,
“Buzz”,
“Fizz”,
“7”,
“8”,
“Fizz”,
“Buzz”,
“11”,
“Fizz”,
“13”,
“14”,
“FizzBuzz”
]

Solution Method

每次做字符串數組的題都要花時間在語法上面。。。

char ** fizzBuzz(int n, int * returnSize)
{
    char f[5] = {'F', 'i', 'z', 'z', '\0'};
    char b[5] = {'B', 'u', 'z', 'z', '\0'};
    char fb[9] = {'F', 'i', 'z', 'z', 'B', 'u', 'z', 'z', '\0'};

    char ** resArr = (char **) malloc (sizeof(char*) * n);  // n個一維數組
    *returnSize = n;

    for (int i = 1; i <= n; i ++)
    {
        resArr[i-1] = (char*) malloc (sizeof(char) * 9);
        memset(resArr[i-1], '\0', sizeof(char) * 9);
        if (i % 15 == 0)
            strcpy(resArr[i-1], fb);
        else if (i % 5 == 0)
            strcpy(resArr[i-1], b);
        else if (i % 3 == 0)
            strcpy(resArr[i-1], f);
        else
            sprintf(resArr[i-1], "%d", i);
        printf("%s\n", resArr[i-1]);
    }
    return resArr;
}

在這裏插入圖片描述

414. Third Maximum Number

Problem Description

Solution Method

本想一次遍歷AC的,但是出現了一些案例不好處理,特別是下面這個

[1,2,-2147483648]

真的坑。

於是選擇遍歷三遍,雖然看起來長,但是效率O(n),如下:

int thirdMax(int* nums, int numsSize)
{
    int max = 0x80000000, sMax = 0x80000000, tMax = 0x80000000, flag = 0;
    
    if (numsSize == 1)
        return nums[0];
    else if (numsSize == 2)
        return nums[0] > nums[1] ? nums[0] : nums[1];

    for (int j = 0; j < numsSize; j ++)
    {
        if (nums[j] > max)
            max = nums[j];
    }

    for (int j = 0; j < numsSize; j ++)
    {
        if (nums[j] > sMax && nums[j] != max)
            sMax = nums[j];
    }
    
    for (int j = 0; j < numsSize; j ++)
    {
        if (nums[j] >= tMax && nums[j] != max && nums[j] != sMax)
        {
            tMax = nums[j];
            flag = 1;
        }
    }
    if (flag == 1)
        return tMax;
    else
        return max;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章