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.
Hint:
- The naive approach is to call
isUglyfor every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
class Solution {
public:
int nthUglyNumber(int n) {
static int i=0, j=0, k=0;
static vector<int> v(1,1);
if (v.size() >= n) return v[n - 1];
while(v.size() < n){
int next = min(v[i] * 2, v[j] * 3, v[k] * 5);
if (next == v[i] * 2) i++;
if (next == v[j] * 3) j++;
if (next == v[k] * 5) k++;
v.push_back(next);
}
return v.back();
}
int min(int a, int b){
return a < b ? a : b;
}
int min(int a, int b, int c) {
return min(min(a, b), c);
}
};
本文介绍了一种高效算法来找到第N个丑数。丑数是指只包含质因数2、3和5的正整数。文章提供了一个C++实现的例子,并探讨了如何通过维护最小丑数的顺序生成丑数序列。
754

被折叠的 条评论
为什么被折叠?



