Ugly Number II

注意负数,所以要使用long,而不能用int

详细解释 请参见http://www.cnblogs.com/julie-yang/p/5147460.html

#include<vector>
#include<queue>
#include<map>
#include<limits>
#include<iostream>
using namespace std;
struct Node{
    long idx;
    long val;
};
struct cmp
{    bool operator()(const Node &a,const Node &b)
    {
        return a.val>b.val;
    }
};
class Solution {
public:
    int nthUglyNumber(int n) {
        priority_queue<Node, vector<Node>, cmp> min_heap;
        vector<int> primes;
        primes.push_back(2);
        primes.push_back(3);
        primes.push_back(5);
        if (primes.size() == 0) return 0;
        map<long, int> start_idx;
        start_idx[1] = 0;
        int res = 1;

        Node temp_node;
        temp_node.idx = 1;     //idx  is the first val of start_idx
        temp_node.val = primes[0];
        min_heap.push(temp_node);
        
        int cnt = 1;
        if (n == 1) return 1;
        long min_val = INT_MAX;

        long min_idx = 0;
        while (cnt < n)
        {
            min_val = min_heap.top().val;
            min_idx = min_heap.top().idx;
            min_heap.pop();
            if ((res != (min_val)))
            {
                res = min_val;
                cnt++;
            start_idx[min_val] = 0;
            temp_node.idx = min_val;     //idx  is the first val of start_idx
            temp_node.val = min_val * primes[0];
            min_heap.push(temp_node);
            
}
            if (start_idx[min_idx] < primes.size() - 1)
            {
                start_idx[min_idx] ++;
                temp_node.idx = min_idx;     //idx  is the first val of start_idx
                temp_node.val = min_idx * primes[start_idx[min_idx]];
                min_heap.push(temp_node);
            
            }
            
        }
        return res;
    }
};

 

你可能感兴趣的:(Ugly Number II)