[leetcode] 264. Ugly Number II 解题报告

46 篇文章 0 订阅

题目链接:https://leetcode.com/problems/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.

Hint:

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
思路:由题目提示可以知道,我们可以依次判断每一个数直到找到第n个丑数,但是因为大多数并不是丑数,由丑数的规律--质因数只有2,3,5,我们可以依次只产生丑数,这样效率会有很大的提高。但是我们要如何保持有序的产生丑数呢?
假设我们现在已经有了一个丑数的有序数组,如果要找到下一个丑数,则可以将数组中的每一个数乘以2,并将其中第一个大于当前丑数的的结果记为M2,同样将当前有序数组每一个数都乘以3,第一个大于当前丑数的的结果记为M3,同样方式得到乘以5的第一个大于当前丑数的结果记为M5。可以下一个丑数必然是min(M2, M3, M5)。
事实上我们并不必要将数组中的每个数都乘以2,3,5。对于乘以2来说,我们只要找到第一个乘以2大于当前丑数的数在数组中的位置,同样找到第一个乘以3,5大于当前丑数的数的位置。如果当前丑数记为M,然后就可以使用min(M*2, M*3, M*5)来产生下一个丑数。
代码如下:
class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> vec{1};
        int ith2 = 0, ith3 = 0, ith5 = 0;
        while(--n > 0)
        {
            int val = min(vec[ith2]*2, min(vec[ith3]*3, vec[ith5]*5));
            vec.push_back(val);
            while(vec[ith2]*2 <= val) ith2++;
            while(vec[ith3]*3 <= val) ith3++;
            while(vec[ith5]*5 <= val) ith5++;
        }
        return vec.back();
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值