priority_queue用法.Ugly Number2

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值