264. Ugly Number II

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, and n does not exceed 1690.

 

题解:

      题目要求求n个丑数,但是丑数的个数不超过1690,因此我可以猜测该题目的对算法复杂度要求不超过O(n^2),实质上求丑数的方法有很多,比如用优先队列,但是在这里我想到一个用来记录下标的方法:假如现在要求第k个丑数,分别记录下上次乘以2,乘以3,乘以5所得到的丑数是多少,这次将对应的数再分别乘2,乘3,乘5,取最小值,就是当前第k个丑数的值。这样的算法复杂度是O(n)是目前想到的比较好的算法。用三个下标,这样做的目的是保证每次都得到大于第k-1个丑数的最小的丑数。

 

代码:

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> res;
        res.push_back(1);
        int ind2,ind3,ind5;
        ind2 = ind3 = ind5 = 0;
        for(int i = 1;i < n;i++)
        {
            res.push_back(min(res[ind2]*2,min(res[ind3]*3,res[ind5]*5)));
            if(res[i]==res[ind2]*2)  ind2++;
            if(res[i]==res[ind3]*3)  ind3++;
            if(res[i]==res[ind5]*5)  ind5++;
        }
        return res[n-1];
    }
};

 

转载于:https://www.cnblogs.com/MT-ComputerVision/p/6825810.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值