描述

把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第 n个丑数。

思路1:暴力破解

对所有数字进行质因数分解

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        int i = 1;
        while(index > 0) {
            if(check(i)){
                index--;
            }
            i++;
        }
        return i - 1;
    }
    //检查是否是质因数
    boolean check(int n) {
        while(n % 2 == 0) {
            n /= 2;
        }
        while(n % 3 == 0) {
            n /= 3;
        }
        while(n % 5 == 0) {
            n /= 5;
        }
        return n == 1;
    }
}

思路2:三指针

丑数=2^x*3^y*5^z

每次计算出下一个丑数,填入数组

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        if(index <= 6) {
            return index;
        }
        int x = 0;
        int y = 0;
        int z = 0;
        int[] res = new int[index];
        res[0] = 1;
        for(int i = 1; i < index; i++) {
            res[i] = Math.min(res[x] * 2, Math.min(res[y] * 3, res[z] * 5));
            if(res[i] == res[x] * 2) {
                x++;
            }
            if(res[i] == res[y] * 3) {
                y++;
            }
            if(res[i] == res[z] * 5) {
                z++;
            }
        }
        return res[index - 1];
    }
}