[LeetCode] 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

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

方法一:

根据[leetcode]263. Ugly Number, https://blog.csdn.net/liuwenyou/article/details/100606158

显然我们可以加一个index来标记是第几个ugly number

 public int nthUglyNumber(int n) {
        if(n==0){
            return 0;
        }
        int index=1;
        int num=1;
        while(index<=n){
            if(isUgly(num)){
                if(index==n){
                    return num;
                }else{
                    num++;
                    index++;
                }
            }else{
                num++;
            }
        }
        return num;
    }
    private boolean isUgly(int m){
        while(true){
            if(m==1){
                return true;
            }else if(m%5==0){
                m/=5;
            }else if(m%3==0){
                m/=3;
            }else if(m%2==0){
                m/=2;
            }else{
                return false;
            }
        }
    }

显然,该算法复杂度很高,一个数一个数的检验是否为ugly number,当n较大时就会超出时间限制。

方法二:

用nums数组来顺序存储ugly number,下一数组元素由之前的nums数组中的元素乘以2或3或5,取且大于前一项的最小的数。

也不必每一个数组元素都要进行这一操作,我们分别用index2,index3,index5来表示要用于乘2,3,5的数组中元素的索引。

public int nthUglyNumber(int n) {
        int []nums=new int[n];//nums数组按序存储ugly number
        nums[0]=1;
        int index2=0,index3=0,index5=0;//分别表示要用来*2 *3 *5的元素的索引
        int i=1;
        while(i<n){
            int m2=nums[index2]*2;
            int m3=nums[index3]*3;
            int m5=nums[index5]*5;
            nums[i]=Math.min(m2,Math.min(m3,m5));//取大于当前ugly number的最小的数
            if(nums[i]==m2){
                index2++;
            }
            if(nums[i]==m3){
                index3++;
            }
            if(nums[i]==m5){
                index5++;
            }
            i++;
        }
        return nums[n-1];
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值