题目描述:
Ugly number is a number that only have factors 2
, 3
and 5
.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Notice
Note that 1
is typically treated as an ugly number.
Example
If n=9
, return 10
.
Challenge
题目思路:
O(n log n) or O(n) time.
利用priority queue的特点,先将第一个ugly number(1)放入pq,从n次循环中,每次取pq中的第一个number也就是最小数,同时放入3个candidates:number * 2, number * 3, number * 5。这样循环n次,第n次得到的number就是所求的number。
Mycode(AC = 31ms):
class Solution {
public:
/*
* @param n an integer
* @return the nth prime number as description.
*/
int nthUglyNumber(int n) {
// write your code here
set<long long> pQueue;
pQueue.insert(1);
long long nth_num = 0;
int ugly_num[3] = {2, 3, 5};
// pop out the smallest number each time
// and the next candidates are:
// smallest_num * [2, 3, 5]
for (int i = 0; i < n; i++) {
nth_num = *pQueue.begin();
pQueue.erase(nth_num);
for (int k = 0; k < 3; k++) {
pQueue.insert(nth_num * ugly_num[k]);
}
}
return (int)nth_num;
}
};