4. 丑数 II【中等】
设计一个算法,找出只含素因子2,3,5 的第 n 小的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
思路:用set去存已求的丑数(去重),用优先队列去存待求的丑数。先让第一个丑数1进set和队列,因为丑数的2、3、5倍也是丑数,所以每次都从队列中取最小的丑数,判断它的2、3、5倍是否判断过,有就忽略,没有就进set和队列,直至求到第n个为止。
代码:
class Solution { public: /* * @param n: An integer * @return: the nth prime number as description. */ int nthUglyNumber(int n) { // write your code here priority_queue<long long,vector<long long>,greater<long long> >q; set<long long> s; q.push(1); s.insert(1); int cnt=1; long long tmp; while(cnt<=n) { tmp=q.top(); q.pop(); cnt++; if(s.find(2*tmp)==s.end()) { s.insert(2*tmp); q.push(2*tmp); } if(s.find(3*tmp)==s.end()) { s.insert(3*tmp); q.push(3*tmp); } if(s.find(5*tmp)==s.end()) { s.insert(5*tmp); q.push(5*tmp); } } return (int)tmp; } };

浙公网安备 33010602011771号