priority_queue用法.Ugly Number2
阿新 • • 發佈:2018-11-11
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();
}