剑指 Offer 49. 丑数

动态规划

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++){
            int n2 = res[a] * 2, n3 = res[b] * 3, n5 = res[c] * 5;
            res[i] = Math.min(n2, Math.min(n3, n5));
            if(res[i] == n2) a++;
            if(res[i] == n3) b++;
            if(res[i] == n5) c++;
        }

        return res[n - 1];
    }
}

优先级队列+哈希表去重

class Solution {
    public int nthUglyNumber(int n) {
        PriorityQueue<Long> pq = new PriorityQueue<>();
        HashSet<Long> set = new HashSet<>();
        int cnt = 0;
        long cur = 0L;
        pq.offer(1L);
        set.add(1L);

        while(cnt < n){
            cur = pq.poll();
            if(!set.contains(cur * 2)){
                pq.offer(cur * 2);
                set.add(cur * 2);
            } 
            if(!set.contains(cur * 3)){
                pq.offer(cur * 3);
                set.add(cur * 3);
            } 
            if(!set.contains(cur * 5)){
                pq.offer(cur * 5);
                set.add(cur * 5);
            } 
            cnt++;
        }

        return (int) cur;
    }
}