您的位置:首页 > 其它

Ugly Number II

2015-08-22 05:48 169 查看
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.

Analyse: We can divide the ugly numbers into three categories:

2: 1*2, 2*2, 3*2, 4*2, 5*2...

3: 1*3, 2*3, 3*3, 4*3, 5*3...

5: 1*5, 2*5, 3*5, 4*5, 5*5...

So our job is to find the first n number in these three arrays. If we already find the i-th smallest number, the next number should be min(l1*2, l2*3, l3*5). The point is that we need to mark the current position of the three arrays, which means that the factor that we want to multiply is the smallest one in the result array. Thus, if the element in one array is selected, then we increase this index.

Runtime: 8ms.

class Solution {
public:
int nthUglyNumber(int n) {
if(n <= 1) return n;

const int len = n;
int ugly
= {1};
int l1 = 0, l2 = 0, l3 = 0;//to represent the current location of the arrays respectively
int f1 = 2, f2 = 3, f3 = 5;//to represent the current ugly factors

for(int i = 1; i < n; i++){
int least = min(min(f1, f2), f3);
if(least == f1) {
ugly[i] = f1;
f1 = 2 * ugly[++l1];
}
if(least == f2){
ugly[i] = f2;
f2 = 3 * ugly[++l2];
}
if(least == f3){
ugly[i] = f3;
f3 = 5 * ugly[++l3];
}
}
return ugly[n - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: