1.问题描述
我们把只包含因子2,3和5的数称作丑数。求按从小到大顺序的第1500个丑数。例如6,8都是丑数,但14不是,因为它包含因子7.习惯上我们把1当做第一个丑数。(来自《剑指offer》)
2.分析
我们设置一个数组,这里面保存着排好序的丑数,因为丑数是按顺序存放在数组中的。对乘以2而言,肯定存在某一个丑数T2,排在它之前的每一个丑数乘以2得到的结果都会小于已有的最大的丑数,在它之后的每一个丑数乘以2得到的结果都会太大。我们只需要记下这个丑数的位置,同时每次生成新的丑数的时候去更新这个T2,对乘以 3 和5而言也同样存在着T3和T5.
3.代码
int Min(int one,int two,int three)
{
int min = one;
if (min > two)
{
min = two;
}
if (min > three)
{
min = three;
}
return min;
}
int GetUglyNumber(int index)
{
if (index <= 0)
{
return 0;
}
int uglyNumber[index];
uglyNumber[0] = 1;
int nextUglyIndex = 1;
int *mutiplay2 = uglyNumber;
int *mutiplay3 = uglyNumber;
int *mutiplay5 = uglyNumber;
while (nextUglyIndex < index)
{
int min = Min(*mutiplay2 * 2,*mutiplay3 * 3,*mutiplay5 * 5);
uglyNumber[nextUglyIndex] = min;
while (*mutiplay2 * 2 <= uglyNumber[nextUglyIndex])
{
mutiplay2++;
}
while (*mutiplay3 * 3 <= uglyNumber[nextUglyIndex])
{
mutiplay3++;
}
while (*mutiplay5 * 5 <= uglyNumber[nextUglyIndex])
{
mutiplay5++;
}
nextUglyIndex++;
}
return uglyNumber[index - 1];
}