> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/heap/264-ugly-number-ii.md).

# 264    Ugly Number II

## 264. [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/description/)

## 1. Question

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**.

## 2. Implementation

**(1) Heap**

```java
class Solution {
    public int nthUglyNumber(int n) {
        PriorityQueue<Long> minHeap = new PriorityQueue<>();
        minHeap.add(1L);

        long curNum = 0;
        for (int i = 0; i < n; i++) {
            curNum = minHeap.remove();

            while (!minHeap.isEmpty() && minHeap.peek() == curNum) {
                curNum = minHeap.remove();
            }

            minHeap.add(2 * curNum);
            minHeap.add(3 * curNum);
            minHeap.add(5 * curNum);
        }
        return (int)curNum;
    }
}
```

## 3. Time & Space Complexity

**Heap:** 时间复杂度O(n \* logn), 空间复杂度O(n)
