zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    [转]double free or corruption (!prev): 0x080644c8 ***
    linux sleep用法
    ubuntu的终端下修改IP、MAC、DNS及GATE
    jmeter mina2总结
    double free or corruption (!prev): 0x080644c8 ***
    jmeter最简单使用
    超级详细Tcpdump 的用法
    eclipse下打开jmeter源码
    Jmeter 命令行选项目录
    JavaScript的一些实用技巧收藏
  • 原文地址:https://www.cnblogs.com/julie-yang/p/5147485.html
Copyright © 2011-2022 走看看