丑数 II

设计一个算法,找出只含素因子235 的第 n 小的数。

符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...

注意事项

我们可以认为1也是一个丑数

样例

如果n = 9, 返回10

挑战

要求时间复杂度为O(nlogn)或者O(n

class Solution {
public:
    /**
     * @param n: An integer
     * @return: the nth prime number as description.
     */
    int nthUglyNumber(int n) {
        // write your code here
        if (n < 1) {
            return 0;
        }
        // always keep in mind that overflow when you see +-*/
        long long nth_Ugly = 0;
        // priority_queue default is max_heap, we can change the heap tyep
        // priority_queue<int, vector<int>, greater<int> > q;  // 小顶堆  
        // priority_queue<int, vector<int>, less<int> > q;     // 大顶堆
        // more details see:https://blog.csdn.net/woshihuangjianwei/article/details/78022521
        priority_queue<long long, vector<long long>, greater<long long> > q;
        q.push(1);
        while (n > 0) {
            nth_Ugly = q.top();
            q.pop();
            while (!q.empty() && q.top() == nth_Ugly) {
                q.pop();
            }
            
            // new value to q;
            q.push(nth_Ugly * 2);
            q.push(nth_Ugly * 3);
            q.push(nth_Ugly * 5);
            
            // next n
            n--;
        }
        return (int)nth_Ugly;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值