您的位置:首页 > 其它

LEETCode 264. Ugly Number II

2016-07-26 20:59 381 查看
问题描述:

Write a program to find the 
n
-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 
2, 3, 5
. For example, 
1,
2, 3, 4, 5, 6, 8, 9, 10, 12
 is the sequence of the first 
10
 ugly numbers.

Note that 
1
 is typically treated as an ugly number.
找第N个丑数,最基础的从1开始判断的方法就不说了,此处的方法是剑指offer上的思路。从1开始遍历的方法复杂度太高,这里只需要考虑到从小到大的开始的每个丑数,都是他前面某个数的2或3或5倍,,因此从已有的丑数1出发,分别诚乘以2、3、5,找出其中最小的一个,得到第二个丑数为2,再找第三个丑数的时候,就要注意到到,由于1乘以2已经出现了,因此下一次是2*2,1*3,1*5,后面的逻辑类似。要注意的时,会出现下一个丑数同时满足多个条件。如6 满足 2*3  也满足3*2  此时 对应的都要更新,不能只更新第一个,所以代码中用的是三个if,而不能是if
、else if
AC代码如下:

int minThree(int x,int y,int z)
{
int temp = x < y ? x : y;
return temp < z ? temp : z;
}
int nthUglyNumber(int n)
{
int count = 0;
int *ugly = new int
;
memset(ugly,0,sizeof(int)*n);
int index1,index2,index3;
index1 = index2 = index3 = 0;
ugly[0] = 1;
while(count < n-1)
{
int No = minThree(2*ugly[index1],3*ugly[index2],5*ugly[index3]);
if(No == 2*ugly[index1])
{
index1++;
}
if(No == 3*ugly[index2])
{
index2++;
}
if(No == 5*ugly[index3])
{
index3++;
}
count++;
ugly[count] = No;
}
return ugly[count];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: