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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:所有的ugly number都是由1开始,乘以2/3/5生成的。
只要将这些生成的数排序即可获得,自动排序可以使用set
这样每次取出的第一个元素就是最小元素,由此再继续生成新的ugly number.
class Solution {
public:
int nthUglyNumber(int n) {
set<long long> order;
order.insert();
int count = ;
long long curmin = ;
while(count < n)
{
curmin = *(order.begin());
order.erase(order.begin());
order.insert(curmin * );
order.insert(curmin * );
order.insert(curmin * );
count ++;
}
return (int)curmin;
}
};