leetcode Ugly Number II

Problem

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.


Solution 1 


最直接的方法,利用 ugly number I 的方法 isUgly( )。对从1开始的每个数字都调用 isUgly( ), 直到第n个数。

Time : O(nlgn)   Space O(1)


Solution 2

稍微数学推导一下,一个数字如果想成为ugly number, 它只能是比它小的ugly number乘以2,3或者5才可以。


也就是说,从1开始,可以用三个指针 idx2, idx3 和 idx5分别指向当前分别乘以2,3,5后有可能成为下一个ugly number的数的位置,

相乘后三个中间最小的那个就是下一个ugly number,并将其index向后移一位。


bug : 如果分别乘以2,3,5后有数相等,那么相等的每个index 都要向后移动一位。

这里我就出错了,害羞害羞  应该是if 语句,我第一次都写成if else 了。

class Solution {
public:
    int nthUglyNumber(int n) {
        vector<int> nums(n, 1);
        int idx2 = 0, idx3 = 0, idx5 = 0;
        for( int i =1; i < n; i++){
            int num2 = nums[idx2]*2, num3 = nums[idx3]*3, num5 = nums[idx5]*5;
            int nextUglyNum = 0;
            if(num2 <= num3 && num2 <= num5){
                nextUglyNum = num2;
                idx2++;
            }
            if( num3 <= num2 && num3 <= num5 ){
                nextUglyNum = num3;
                idx3++;
            }
            if( num5 <= num2 && num5 <= num3) {
                nextUglyNum = num5;
                idx5++;
            }

            nums[i] = nextUglyNum;
        }
        return nums[n-1];   
    }
};



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值