标签:c语言 剑指offer 面试题 把只含因子2、3和5的数称为丑数 求第1500个丑数 优化
把只含因子2、3和5的数称为丑数,求按从小到大的顺序的第1500个丑数。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上把1当作第1个丑数。
算法1:逐个判断每个整数是不是丑数的解法,直观但不够高效
#include<stdio.h>
int ugly(int number)
{
while (number % 2 == 0)
{
number /= 2;
}
while (number % 3 == 0)
{
number /= 3;
}
while (number % 5 == 0)
{
number /= 5;
}
return (number == 1) ? 1 : 0;
}
int fun(int num)
{
if (num <= 0)
{
return 0;
}
int number = 0;
int uglyfound = 0;
while (uglyfound < num)
{
++number;
if (ugly(number))
{
++uglyfound;
}
}
return number;
}
int main()
{
int num = 0, ret = 0;
printf("请输入一个丑数的序号:");
scanf("%d", &num);
ret = fun(num);
printf("number=%d\n", ret);
return 0;
}
算法2:不需要在非丑数的整数上做任何计算,时间效率明显提升,但是由于需要保存已经生成的丑数,增加了空间消耗,相当于用空间消耗换取了时间效率的提升。主要代码如下:
int Min(int number1, int number2, int number3);
int GetUglyNumber_Solution(int index)
{
if (index <= 0)
return 0;
int *pUglyNumbers = new int[index];
pUglyNumbers[0] = 1;
int nextUglyIndex = 1;
int *pMultiply2 = pUglyNumbers;
int *pMultiply3 = pUglyNumbers;
int *pMultiply5 = pUglyNumbers;
while (nextUglyIndex < index)
{
int min = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
pUglyNumbers[nextUglyIndex] = min;
while (*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
++pMultiply2;
while (*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3;
while (*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5;
++nextUglyIndex;
}
int ugly = pUglyNumbers[nextUglyIndex - 1];
delete[] pUglyNumbers;
return ugly;
}
int Min(int number1, int number2, int number3)
{
int min = (number1 < number2) ? number1 : number2;
min = (min < number3) ? min : number3;
return min;
}
结果:
请输入一个丑数的序号:1500
number=859963392
请按任意键继续. . .
本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1743483
c语言:把只含因子2、3和5的数称为丑数,求按从小到大的顺序的第1500个丑数(两种方法比较)
标签:c语言 剑指offer 面试题 把只含因子2、3和5的数称为丑数 求第1500个丑数 优化
原文地址:http://yaoyaolx.blog.51cto.com/10732111/1743483