1.priority_queue的本质是数据结构中的堆
2.头文件在#include< queue>
3.关于priority_queue中元素的比较
使用模板:priority_queue< Type, Container, Functional>,其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。
priority_queue默认为大顶堆,即堆顶元素为堆中最大元素。如果我们想要用小顶堆的话需要增加使用两个参数:
priority_queue< int, vector< int>, greater< int> > q; // 小顶堆
priority_queue< int, vector< int>, less< int> > q; // 大顶堆
case
name:Ugly number 2
Ugly number is a number that only have factors 2, 3 and 5.
Design an algorithm to find the nth ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12…
Example
If n=9, return 10.
int nthUglyNumber(int n) {
priority_queue<long,vector<long>,greater<long>>qu;//小顶堆
qu.push(1);
if(n==1) return 1;
for(int i=1;i<n;i++){
long tmp=qu.top();
qu.push(tmp*2);
qu.push(tmp*3);
qu.push(tmp*5);
while(qu.top()==tmp){
qu.pop();
}
}
return qu.top();
}