0602-2020-LEETCODE-经典.49-寻找第N个丑数(dp)

自己写的超时版本,每次计算没有用到之前的计算结果。

	public int nthUglyNumber(int n) {
        if (n == 1) return 1;
        int[] arr = new int[n];
        arr[0] = 1;
        int index = 1;
        int num = 2;
        while (index < n){
            if (isUgly(num)){
                arr[index++] = num;
            }
            num++;
        }
        return arr[n - 1];
    }

     private boolean isUgly(int n) {
        while (n != 1){
            if (n % 2 == 0){
                n /= 2;
            } else if (n % 3 == 0){
                n /= 3;
            } else if (n % 5 == 0){
                n /= 5;
            } else {
                break;
            }
        }
         return n == 1;
     }

自己模仿题解写的,while循环会增加很多不必要的判断导致代码的效率降低。

public int nthUglyNumber1(int n) {
        int[] res = new int[n];
        res[0] = 1;
        int indexA = 0;
        int indexB = 0;
        int indexC = 0;
        int count = 0;
        int tempA = 0, tempB = 0,tempC = 0;
        while (count < n - 1){
            if ((tempA = res[indexA] * 2) <= res[count]) indexA++;
            else if ((tempB = res[indexB] * 3) <= res[count]) indexB++;
            else if ((tempC = res[indexC] * 5) <= res[count]) indexC++;
            else {
                res[++count] = Math.min(Math.min(tempA,tempB),tempC);
            }
        }
        return res[n - 1];
    }

优秀的写法,少判断了很多次。

	public int nthUglyNumber2(int n) {
        int[] res = new int[n];
        res[0] = 1;
        int indexA = 0;
        int indexB = 0;
        int indexC = 0;
        for (int i = 1; i < n; i++) {
            int tempA = 2 * res[indexA], tempB = 3 * res[indexB],tempC = 5 * res[indexC];
            res[i] = Math.min(Math.min(tempA,tempB),tempC);
            if (tempA == res[i]) indexA++;
            if (tempB == res[i]) indexB++;
            if (tempC == res[i]) indexC++;
        }
        return res[n - 1];
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值