0
点赞
收藏
分享

微信扫一扫

Ugly Number II 寻找第N个丑数

芭芭蘑菇 2023-02-17 阅读 66


Ugly Number II


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​​sequence of the first ​​10​​Note that ​​1​

class Solution {
public:
int nthUglyNumber(int n) {

/*
超时
if(n==1)
return 1;
int k=1;
int tmp;
int ans=1;
while(k<n)
{
tmp=++ans;
while(1)
{
while(tmp%2==0)
tmp/=2;
while(tmp%3==0)
tmp/=3;
while(tmp%5==0)
tmp/=5;
if(tmp==1)
break;
else
tmp=++ans;
}
k++;
}
return ans;
*/

//记住14不是的,不能用3个index,然后遍历比较
//因为每个丑数都是前面的丑数*2,*3,*5得到,所以要从以前的数中拿取

int *ans=new int[n+1];
ans[0]=1;
int index=1;
int i=0,j=0,k=0;
while(index<n)
{
ans[index]=min(ans[i]*2,min(ans[j]*3,ans[k]*5));
if(ans[index]==ans[i]*2)
i++;
if(ans[index]==ans[j]*3)
j++;
if(ans[index]==ans[k]*5)
k++;
index++;
}
return ans[index-1];

}
};

举报

相关推荐

0 条评论