2015年9月1日星期二

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.

public class Solution {
    public int nthUglyNumber(int n) {
        PriorityQueue<Integer> queue = new PriorityQueue(4);
        queue.add(1);
        int order = 1;
        int top = 1;
        while (order <= n) {
            top = queue.poll();
            if (top < Integer.MAX_VALUE / 2 && !queue.contains(top * 2)) queue.add(top * 2);
            if (top < Integer.MAX_VALUE / 3 && !queue.contains(top * 3)) queue.add(top * 3);
            if (top < Integer.MAX_VALUE / 5 && !queue.contains(top * 5)) queue.add(top * 5);
            order++;
        }
        return top;
    }
}

========

public class Solution {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[n + 1];
        int i2 = 0;
        int i3 = 0;
        int i5 = 0;
        int factor2 = 2;
        int factor3 = 3;
        int factor5 = 5;
        ugly[0] = 1;
        for (int i = 1; i < n; i++) {
            int min = Math.min(factor2, Math.min(factor3, factor5));
            ugly[i] = min;
            if (min == factor2) {
                i2++;
                factor2 = 2 * ugly[i2];
            }
            if (min == factor3) {
                i3++;
                factor3 = 3 * ugly[i3];
            }
            if (min == factor5) {
                i5++;
                factor5 = 5 * ugly[i5];
            }
        }
        return ugly[n - 1];
    }
}

========

public class Solution {
    public int nthUglyNumber(int n) {
        int id2 = 0, id3 = 0, id5 = 0;
        int arr[] = new int[n];
        arr[0] = 1;
        int min = 1;
        for (int i = 1; i < n; i++) {
            min = Math.min(arr[id2] * 2, Math.min(arr[id3] * 3, arr[id5] * 5));
            if (min == arr[id2] * 2) id2++;
            if (min == arr[id3] * 3) id3++;
            if (min == arr[id5] * 5) id5++;
            arr[i] = min;
        }
        return arr[n - 1];
    }
}

没有评论:

发表评论