Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1 is typically treated as an ugly number. n does not exceed 1690.
丑数都是2,3,5的倍数,从1开始2,3,5得2,3,5,取其中最小值2再2,3,5得4,6,10。建一个PriorityQueue,把不重复的值存在queue中,每次剔除出最小值来2,3,*5,这样到第n个循环时候剔除出来的最小值就是第n个丑数。
class Solution {
public int nthUglyNumber(int n) {
PriorityQueue<Long> queue = new PriorityQueue<>();
if(n == 1) return 1;
long res = 1;
queue.add(res);
for(int i = 1; i <= n; i++) {
res = queue.poll();
if(!queue.contains(res * 2)) queue.add(res * 2);
if(!queue.contains(res * 3)) queue.add(res * 3);
if(!queue.contains(res * 5)) queue.add(res * 5);
}
return (int)res;
}
}