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, and n does not exceed 1690.
比较直接的思路是判断每个数是不是丑陋数,但效率过低.行之有效的方法是由已有的丑陋数乘2,乘3,乘5得出新的丑陋数,为得到第n个丑陋数,这要求我们要按照从小到大的顺序生成丑陋数.一个小的丑陋数乘5,可能比一个大的丑陋数乘5要大,也可能小.为了确定新的最小的丑陋数是如何生成的,需要有三个指针跟踪丑陋数,这三个指针指向的值分别乘2,乘3,乘5,新的丑陋数是三个数的最小数.为了防止重复,生成新的丑陋数的指针需要向后移动.
class Solution {
public:
int nthUglyNumber(int n) {
if (n <= 0) return -1;
vector<int> nums;
nums.push_back(1);
int cnt = 1;
int cur2 = 0, cur3 = 0, cur5 = 0;
int next = min(2 * nums[cur2], min(3 * nums[cur3], 5 * nums[cur5]));
while (cnt < n){
nums.push_back(next);
++cnt;
if (next == 2 * nums[cur2]) ++cur2;
if (next == 3 * nums[cur3]) ++cur3;
if (next == 5 * nums[cur5]) ++cur5;
next = min(2 * nums[cur2], min(3 * nums[cur3], 5 * nums[cur5]));
}
return nums[n-1];
}
};