丑数

89 阅读1分钟

丑数

我们把只包含质因子2、3和5的数称作丑数(Ugly Number)。

例如6、8都是丑数,但14不是,因为它包含质因子7。

求第n个丑数的值。
注意:习惯上我们把1当做第一个丑数。

样例
输入:5
输出:5

数学

时间复杂度O(n)

class Solution {
    public int getUglyNumber(int n) {
        if(n <= 0){
            return 0;
        }
        int[] res = new int[n];
        res[0] = 1;
        int next = 1;
        int u2 = 0,u3 = 0,u5 = 0;
        while(next < n){
            int temp = Math.min(2 * res[u2],Math.min(3 * res[u3],5 * res[u5]));
            res[next++] = temp;
            if(2 * res[u2] == temp) u2++;
            if(3 * res[u3] == temp) u3++;
            if(5 * res[u5] == temp) u5++;
        }
        return res[n-1];
    }
}