-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathNthUglyNumber.java
More file actions
37 lines (29 loc) · 802 Bytes
/
Copy pathNthUglyNumber.java
File metadata and controls
37 lines (29 loc) · 802 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.lga.algorithm.tag.homework.Week_02;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
/**
* 剑指 Offer 49. 丑数
* https://leetcode-cn.com/problems/chou-shu-lcof/
*/
public class NthUglyNumber {
/**
* 构建最小堆依次弹出
* @param n
* @return
*/
public int nthUglyNumber(int n) {
PriorityQueue<Long> minHeap = new PriorityQueue<>();
int[] nums = new int[]{2, 3, 5};
minHeap.add(1L);
int count = 0;
while (!minHeap.isEmpty()) {
long cur = minHeap.poll();
if(++count == n) return (int) cur;
for (int num : nums) {
if (!minHeap.contains(cur*num)) minHeap.add(cur * num);
}
}
return -1;
}
}