LintCode----4.丑数II

原题目

1.暴力

暴力就是从1开始循环然后判断是不是丑数。数据量大的时候直接超时,不过逻辑是正确的,过掉94%


public class Main {

//是不是丑数
    public boolean isUgly(int n) {
        boolean result = false;
        if (n == 1) {
            return !result;
        }
        if (isOk(n)) {
            while (n % 2 == 0) {
                n = n >>1;
            }
            while (n % 3 == 0) {
                n = n / 3;
            }
            while (n % 5 == 0) {
                n = n / 5;
            }
            if (n == 1) {
                result = true;
            }
        }
        return result;
    }


    public boolean isOk(int n) {
        boolean result = false;
        if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0) {
            result = true;
        }
        return result;
    }

    public int nthUglyNumber(int n) {
        int counter = 0;
        int result = 0;
        for (int i = 1; ; i++) {
            if (isUgly(i)) {
                counter++;
            }
            if (counter == n) {
                result = i;
                break;
            }
        }
        return result;
    }


    public static void main(String[] args) {

        Main main = new Main();
        System.out.println(main.nthUglyNumber(41));
    }
}

2.合成

我们可以直接从要求入手单手合成丑数,然后根据我们操作的次数来结束战斗。思路就是要找到最接近前一个数的值,然后分别*2,*3,*5再来取得最小值就是结果了。参考九章算数


import java.util.*;
import java.lang.*;
public class Solution {
    public int nthUglyNumber(int n) {
        int p2 = 0;
        int p3 = 0;
        int p5 = 0;
        List<Integer> ugly = new ArrayList<>();
        ugly.add(1);
        for (int i = 1; i < n; i++) {

            int temp = ugly.get(i - 1);
            while (ugly.get(p2) * 2 <= temp) {
                p2++;
            }
            while (ugly.get(p3) * 3 <= temp) {
                p3++;
            }
            while (ugly.get(p5)*5 <= temp) {
                p5++;
            }
            ugly.add(Math.min(Math.min(ugly.get(p2)*2,ugly.get(p3)*3),ugly.get(p5)*5));
        }
        return ugly.get(n-1);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值