0264. Ugly Number Ⅱ (M)

Ugly Number II (M)

題目

Write a program to find the n-th ugly number.javascript

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.html

Example:java

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:es5

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

題意

找到第n個因數只有二、三、5的整數。code

思路

  1. 自底向上生成第n個醜陋數:每一個醜陋數均可以由以前的某一個醜陋數乘2或3或5獲得。所以記錄下二、三、5要乘的下一個醜陋數的下標,每一次從獲得的三個數中選取最小的一個做爲新的醜陋數加入列表中,並根據這個值將二、三、5要乘的下一個下標日後挪一位。以下圖示例:

  1. 堆:用小頂堆存儲醜陋數,每次取堆頂的數x做爲最新的醜陋數,並將全部與x相同的數除去,最後再往堆裏存入2x、3x、5x。重複操做n次後獲得的就是第n個醜陋數。(注意這種方法每次都是用最新的醜陋數去乘二、三、5,所以可能出現int越界的狀況,因此堆必須用long)

代碼實現

Java

迭代

class Solution {
    public int nthUglyNumber(int n) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        int times2pos = 0, times3pos = 0, times5pos = 0;
        while (list.size() < n) {
            int times2 = list.get(times2pos) * 2;
            int times3 = list.get(times3pos) * 3;
            int times5 = list.get(times5pos) * 5;
            int min = Math.min(Math.min(times2, times3), times5);
            if (min == times2) times2pos++;
            if (min == times3) times3pos++;
            if (min == times5) times5pos++;
            list.add(min);
        }
        return list.get(list.size() - 1);
    }
}

class Solution {
    public int nthUglyNumber(int n) {
        Queue<Long> heap = new PriorityQueue<>();
        heap.offer(1l);
        int count = 0;
        long ans = 0;
        while (count != n) {
            ans = heap.poll();
            while (!heap.isEmpty() && heap.peek() == ans) {
                heap.poll();
            }
            heap.offer(ans * 2);
            heap.offer(ans * 3);
            heap.offer(ans * 5);
            count++;
        }
        return (int)ans;
    }
}

JavaScript

/**
 * @param {number} n
 * @return {number}
 */
var nthUglyNumber = function (n) {
  let list = [1]
  let pos2 = 0, pos3 = 0, pos5 = 0
  while (list.length < n) {
    let times2 = list[pos2] * 2
    let times3 = list[pos3] * 3
    let times5 = list[pos5] * 5
    let min = Math.min(times2, times3, times5)
    if (min === times2) pos2++
    if (min === times3) pos3++
    if (min === times5) pos5++
    list.push(min)
  }
  return list[n - 1]
}

參考htm

[LeetCode] 264. Ugly Number II 醜陋數之二blog

相關文章
相關標籤/搜索