Ugly Number II

描述

Write a function 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.

Hint:

  1. The naive approach is to call isUgly() for every number until you reach the n-th one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1L_1, L2L_2, and L3L_3.
  4. Assume you have UkU_k, the kthk^{th} ugly number. Then Uk+1U_{k+1} must be Min(L12,L23,L35)Min(L_1 * 2, L_2 * 3, L_3 * 5).

分析

根据提示中的信息,我们知道丑陋序列可以拆分成3个子序列:

  1. 1x2, 2x2, 3x2, 4x2, 5x2, ...
  2. 1x3, 2x3, 3x3, 4x3, 5x3, ...
  3. 1x5, 2x5, 3x5, 4x5, 5x5, ...

每次从三个列表中取出当前最小的那个加入序列,直到第n个为止。

代码

// Ugly Number II
// Time complexity: O(n), Space complexity: O(n)
// TODO: 没必要保存所有的ugly number, 空间可以优化到O(1)
public class Solution {
    public int nthUglyNumber(int n) {
        final int[] nums = new int[n];
        nums[0] = 1; // 1 is the first ugly number
        int index = 0, index2 = 0, index3 = 0, index5 = 0;

        while (index + 1 < n) {
            int x2 = nums[index2] * 2;
            int x3 = nums[index3] * 3;
            int x5 = nums[index5] * 5;
            int min = Math.min(x2, Math.min(x3, x5));

            if (min == x2) ++index2;
            else if (min == x3) ++index3;
            else ++index5;

            if (min != nums[index]) { // skip duplicate
                nums[++index] = min;
            }
        }
        return nums[n - 1];
    }
}

相关题目

results matching ""

    No results matching ""