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. 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.

Ideas:

设置4个Index,一个i和三个t2, t3, t5

l[i] = Math.min(l[t2]*2, Math.min(l[t3]*3, l[t5]*5));
if (l[i] == l[t2]*2) t2++;
if (l[i] == l[t3]*3) t3++;
if (l[i] == l[t5]*5) t5++;

Code:

public int nthUglyNumber(int n) {
    if (n <= 0) return 0;

    int[] l = new int[n];
    l[0] = 1;

    int i = 1;
    int t2 = 0, t3 = 0, t5 = 0;
    while(i < n) {
        l[i] = Math.min(l[t2]*2, Math.min(l[t3]*3, l[t5]*5));
        if (l[i] == l[t2]*2) t2++;
        if (l[i] == l[t3]*3) t3++;
        if (l[i] == l[t5]*5) t5++;

        i++;
    }

    return l[n-1];
}

results matching ""

    No results matching ""