码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Ugly Number II

时间:2015-12-04 22:43:05      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

题目连接

https://leetcode.com/problems/ugly-number-ii/  

Ugly Number II

Description

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.

class Solution {
private:
    typedef unsigned long long int ull;
    struct cmp {
        bool operator()(const ull a, const ull b) {
            return a > b;
        }
    };
public:
    int nthUglyNumber(int n) {
        ull lb = 0, ub = 0, arr[3] = { 2, 3, 5 };
        priority_queue<ull, vector<ull>, cmp > q;
        q.push(1);
        for (int i = 1; i <= n;) {
            ull val = q.top(); q.pop();
            ub = val;
            if (ub == lb) {
                continue;
            } else {
                lb = val;
                i++;
            }
            for (int j = 0; j < 3; j++) q.push(val * arr[j]);
        }
        return (int)lb;
    }
};

leetcode Ugly Number II

标签:

原文地址:http://www.cnblogs.com/GadyPu/p/5020591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!