多指针

https://leetcode.com/problems/ugly-number-ii/description/

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.

Thoughts

新的丑数都是由已有丑数乘以2, 3或5得来的,因此需要指针track该哪个数*2, 3或5。问题在于常规DP只用一个指针,而下一个数不一定是f[i-1]*2,3或5. 由于任何一个数都可以乘以2,3,5构成新的丑数, 那我们何不维持3个指针分别指向还没有乘2,3或5的丑数 ,让它们 分别与对应丑数相乘找最小并移动相应指针。

Code

class Solution {
    public int nthUglyNumber(int n) {
        int[] f = new int[n];
        f[0] = 1;

        int k2 = 0, k3 = 0, k5 = 0;
        for (int i = 1; i < n; i++) {
            f[i] = Math.min(f[k2] * 2, Math.min(f[k3] * 3, f[k5] * 5));
            if (f[i] == f[k2] * 2) k2++;
            if (f[i] == f[k3] * 3) k3++;
            if (f[i] == f[k5] * 5) k5++;
        }

        return f[n - 1];
    }
}

Analysis

Errors:

  1. 不是k2 * 2

  2. 也不是fi-1] * 2.

时间复杂度O(n)

Last updated