面试题49:丑数
文章目录
题目
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
考点
一个丑数可由另一个丑数乘以2,3,5得到
1是丑数
LeetCode版本
class Solution {
public:
int minNum(int a, int b, int c){
int res ;
res = a<b?a:b;
res = res<c?res:c;
return res;
}
int nthUglyNumber(int n) {
int t2(0), t3(0), t5(0);
int *uglynum = new int[n];
uglynum[0] = 1;
for(int i = 1; i < n; i++){
int a = uglynum[t2]*2, b = uglynum[t3]*3, c= uglynum[t5]*5;
int temp = minNum(a,b,c);
uglynum[i] = temp;
if(temp == a) ++t2;
if(temp == b) ++t3;
if(temp == c) ++t5;
}
return uglynum[n-1];
}
};