Leetcode 0264: 丑数 II Ugly Number II

Title description:

Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Chinese description:

Write a program to find the nth ugly number.
Ugly numbers are positive integers whose prime factors only contain 2, 3, and 5.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:

1 is typically treated as an ugly number.
n does not exceed 1690.

Time complexity: O O O (NNN ) The
three pointers are merged: the
pointers i, j, and k are pointers to the ugly number arrays S2, S3, and S5 containing 2, 3, and 5 respectively.
S2: { 1 × 2 1\times2 1×2, 2 × 2 2\times2 2×2, 3 × 2 3\times2 3×2, 4 × 2 4\times2 4×2, 5 × 2 5\times2 5×2, 6 × 2 6\times2 6×2, 8 × 2 8\times2 8×2 ,…}
S3: { 1 × 3 1 \ times3 1×3, 2 × 3 2\times3 2×3, 3 × 3 3\times3 3×3, 4 × 3 4\times3 4×3, 5 × 3 5\times3 5×3, 6 × 3 6\times3 6×3, 8 × 3 8\times3 8×3 ,…}
S3: { 1 × 5 1 \ times5 1×5, 2 × 5 2\times5 2×5, 3 × 5 3\times5 3×5, 4 × 5 4\times5 4×5, 5 × 5 5\times5 5×5, 6 × 5 6\times5 6×5, 8 × 5 8\times5 8×5 , …}
Through observation, we find that there is a basic arraySSS: { 1 1 1, 2 2 2, 3 3 3, 4 4 4, 5 5 5, 6 6 6, 8 8 8,…}
S2 = S × 2 S\times2 S×2, S3 = S × 3 S\times3 S×3, S5 = S × 5 S\times5 S×5 .
Therefore, we use this basis the number of the array Ugly and 2,3,5 multiplying the minimum value of the next number is the beginning of an ugly and moves from the corresponding pointer. Note that when there are more than one satisfying, the pointer that satisfies the condition must be moved, such as the sixth ugly number: 6. S2 in3 × 2 3\times23×2 = 6 The pointer is 3, to move to 4. At the same time,2 × 3 2\times3 in S32×3 = 6 The pointer is 2, which needs to be moved to 3.

class Solution {
    
    
    public int nthUglyNumber(int n) {
    
    
        int[] res = new int[n];
        int i = 0,j = 0,k = 0;
        res[0] = 1;
        for(int index = 1; index < n;index++){
    
    
            int t = Math.min(Math.min(res[i]*2, res[j]*3), res[k]*5);
            res[index] = t;
            if(res[i]*2 == t) i++;
            if(res[j]*3 == t) j++;
            if(res[k]*5 == t) k++;
        }
        return res[n-1];
    }
}

Guess you like

Origin blog.csdn.net/weixin_43946031/article/details/114080298