Ugly Number II
2016-01-21 10:43
218 查看
注意负数,所以要使用long,而不能用int
详细解释 请参见http://www.cnblogs.com/julie-yang/p/5147460.html
详细解释 请参见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; } };
相关文章推荐
- 关于烂代码的那些事(上)
- viewPager的简单使用
- 系统最大连接数
- Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity
- Android——systembroadcast 列表
- Android——permission 列表
- centos apache IE8兼容
- nodejs学习笔记<安装和配置>
- Java中方法的重载与覆写的区别
- Jquery三级菜单切换
- webstorm 设置jsp支持ZenCoding
- 【转】VS2010发布、打包安装程序(超全超详细)
- symfony配置
- 【老生常谈】Attr与Prop的区别
- html 选择图片后马上展示出来
- 谈谈C#中的内存分配
- spring概念整理
- Android Error: ShouldNotReachHere()
- POJ 1087 A Plug for UNIX(Dinic)
- Android中PopupWindow的使用