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. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

一刷
题解:


264. Ugly Number II_第1张图片

用三个队列,保存2,3,4乘上ugly number后的值,注意,为了避免重复,2的队列不乘3,5队列中的值,3中不乘5队列中的值。

public class Solution {
    public int nthUglyNumber(int n) {
        if(n<1) return 0;
        
        Queue q2 = new LinkedList<>();
        Queue q3 = new LinkedList<>();
        Queue q5 = new LinkedList<>();
        q2.add(2L);
        q3.add(3L);
        q5.add(5L);
        Long res = 1L;
        
        while(n>1){
            if(q2.peek() < q3.peek() && q2.peek() < q5.peek()){
                res = q2.poll();
                q2.add(res*2);
                q3.add(res*3);
                q5.add(res*5);
            }
            else if(q3.peek() < q2.peek() && q3.peek() < q5.peek()){
                res = q3.poll();
                q3.add(res*3);
                q5.add(res*5); 
            } else{
                res = q5.poll();
                q5.add(res*5);
            }
        }
        
        return res.intValue();
    }
}

但是这样会出现超时,改用array, 并用3个index记录下一个*2/3/5的值

public class Solution {
    public int nthUglyNumber(int n) {
        if (n <= 0) return 0;
        int[] dp = new int[n];
        dp[0] = 1;
        int index2 = 0, index3 = 0, index5 = 0;
        for (int i = 1; i < n; i++) {
            dp[i] = Math.min(2 * dp[index2], Math.min(3 * dp[index3], 5 * dp[index5]));
            if (dp[i] == 2 * dp[index2]) index2++;
            if (dp[i] == 3 * dp[index3]) index3++;
            if (dp[i] == 5 * dp[index5]) index5++;
        }
        return dp[n - 1];
    }
}

二刷
同上

public class Solution {
    public int nthUglyNumber(int n) {
        if(n<=0) return 0;
        int[] dp = new int[n];
        dp[0] = 1;
        int index2 = 0, index3 = 0, index5=0;
        for(int i=1; i

index2与index3,index5可以通过同一个数一起增加,比如index2 = 3, index3 = 2, 当前最小的数为6,那么index2++, index3++

你可能感兴趣的:(264. Ugly Number II)