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, and n does not exceed 1690.

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Solution

public class Solution {
      public int nthUglyNumber(int n) {

        PriorityQueue<Long> priorityQueue = new PriorityQueue<>();
        priorityQueue.add((long) 1);
        priorityQueue.add((long) 2);
        priorityQueue.add((long) 3);
        priorityQueue.add((long) 5);

        int index = 0;
        while (!priorityQueue.isEmpty()) {
            Long current = priorityQueue.poll();

            if (!priorityQueue.contains(current * 2)) {
                priorityQueue.add(current * 2);
            }

            if (!priorityQueue.contains(current * 3)) {
                priorityQueue.add(current * 3);
            }

            if (!priorityQueue.contains(current * 5)) {
                priorityQueue.add(current * 5);
            }

            index += 1;

            if (index == n) {
                return current.intValue();
            }
        }

        return -1;
    }
}

results matching ""

    No results matching ""