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
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
isUgly
for 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).
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Hide Tags
Hide Similar Problems
(H) Merge k Sorted Lists (E) Count Primes (E) Ugly Number
刚开始想的是分三个数列,2,3,5 各一个,然后依次取最小值,就像提示说的一样。
显然不能直接用自然数去产生着三个数列,那就是要利用已经产生的结果了。
进一步观察发现不需要三个数列,只需要三个下标,标识出 2,3,5 分别已经产生到哪个数字了,下次用它来乘以 2,3,5 就好了。
class Solution {
public:
int nthUglyNumber(int n) {
if(n<1)
return 0;
int id2=0, id3=0, id5=0, rst=1;
vector<int> buf;
while(--n)
{
buf.push_back(rst);
int v2 = 2*(buf[id2]), v3 = 3*(buf[id3]), v5 = 5*(buf[id5]);
rst = min(v2, min(v3, v5));
id2 += (rst == v2), id3 += (rst == v3), id5 += (rst == v5);
}
return rst;
}
};
16 ms.
No comments:
Post a Comment