264.leetcode Ugly Number II(medium)[寻找第N个丑数]

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number.

之前有个题目是判断是一个数是否为丑数,按照常规思路应该是从1开始顺序查找判断是否为丑数,但是这样效率不高;因此维护3个队列,分别为乘2的丑数,乘3的丑数和乘5丑数的队列,丑数一定是前面2,3,5乘以2,3,5得到的数字。因此每次从队列首部取出三个数字中最小的数字作为第k个丑数,同时乘以2,3,5放入队尾。

class Solution {
public:
    int getMin(int a,int b,int c)
    {
        int temp = a>b?b:a;
        return temp>c?c:temp;
    }
    int nthUglyNumber(int n) {
        list<int> q2;
        list<int> q3;
        list<int> q5;
        int count = 1;
        int num = 1;
        while(count != n)
        {
            q2.push_back(2*num);
            q3.push_back(3*num);
            q5.push_back(5*num);
            int a = q2.front();
            int b = q3.front();
            int c = q5.front();
            int min = getMin(a,b,c);
            if(min == a) q2.pop_front();
            if(min == b) q3.pop_front();
            if(min == c) q5.pop_front();
            ++count;
            num = min;
        }
        return num;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值