Leetcode 0264: 丑数 II 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.

中文描述:

编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 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( N N N)
三个指针合并:
指针i,j, k 分别是包含2,3,5 的丑数数组S2,S3,S5的指针。
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, …}
通过观察我们发现 有一个基础数组 S S S: { 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.
所以,我们从1开始以此把基础丑数数组的数与2,3,5 相乘最小的即为下一个丑数的值且移动对应的指针。注意当有多个满足时,满足条件的指针都要移动,如 对于第6个丑数:6。S2 中 3 × 2 3\times2 3×2 = 6 指针为3,要移动到4. 同时,S3 中 2 × 3 2\times3 2×3 = 6 指针为2,要移动到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];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/114080298