BiruLyu
8/5/2017 - 11:02 PM

264. Ugly Number II(dp).java

public class Solution {
    public int nthUglyNumber(int n) {
        if(n == 1){
            return 1;
        }
        PriorityQueue<Long> q = new PriorityQueue<Long>();
        q.add(1l);
        
        for(long i = 1; i < n; i++) {
            long tmp = q.poll();
            while(!q.isEmpty() && q.peek() == tmp) {
                tmp = q.poll();
            }
            q.offer(tmp*2);
            q.offer(tmp*3);
            q.offer(tmp*5);
        }
        return q.poll().intValue();
    }
}
public class Solution {
    public int nthUglyNumber(int n) {
        int a = 0, b = 0, c = 0;
        int[] res = new int[n];
        res[0] = 1;
        for (int i = 1; i < n; i++) {
            res[i] = Math.min(res[a] * 2, Math.min(res[b] * 3, res[c] * 5));
            if (res[i] == res[a] * 2) a++;
            if (res[i] == res[b] * 3) b++;
            if (res[i] == res[c] * 5) c++;
        }
        return res[n - 1];
    }
}