Java Solution using heap


  • -2
    J
    public class Solution {
    

    public int nthUglyNumber(int n) {
    if(n < 1) {
    return 0;
    }
    if(n == 1) {
    return 1;
    }
    PriorityQueue<Long> heap = new PriorityQueue<Long>();
    heap.offer((long)1);
    int count = 1;
    long uglyNumber = 0;
    while(count != n + 1) {
    while(heap.peek() == uglyNumber) {
    heap.poll();
    }
    uglyNumber = heap.poll();
    heap.offer(uglyNumber * 2);
    heap.offer(uglyNumber * 3);
    heap.offer(uglyNumber * 5);
    count++;
    }
    return (int)uglyNumber;
    }
    }be aware of overflow


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.