4. ugly number ii

explanation

  1. method 1: scan O(n)
    后面的数根据前面的数生成
  2. method 2: Priority Queue O(nlogn) 待写

    code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27

    class {
    /**
    * @param n an integer
    * @return the nth prime number as description.
    */
    public int nthUglyNumber(int n) {
    // 只有2,3,5 这三个factor
    int[] ugly = new int[n];
    int p2 = 0, p3 = 0, p5 = 0;
    ugly[0] = 1;
    for (int i = 1; i < n; i++) {
    ugly[i] = Math.min(ugly[p2] * 2, Math.min(ugly[p3] * 3, ugly[p5] * 5));
    // 有可能p2 * 2, p3 * 3, p5 * 5有一样的数,都要加一
    if (ugly[i] == ugly[p2] * 2) {
    p2++;
    }
    if (ugly[i] == ugly[p3] * 3) {
    p3++;
    }
    if (ugly[i] == ugly[p5] * 5) {
    p5++;
    }
    }
    return ugly[n - 1];
    }
    }