文章目录
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;
}