categories: leetcode

题目描述
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. `1` is typically treated as an ugly number.1. `n` **does not exceed 1690**.<a name="36967e2c"></a>## 参考代码```javaclass Solution {public int nthUglyNumber(int n) {int factors[] = {2,3,5};//优先队列Queue<Long> queue = new PriorityQueue<>();queue.offer(1L);注意第1690个可能会超过int的范围while (true) {long min = queue.poll();//每次取最小值相乘,取得第n个数if (n == 1) {return (int)min;}for (int i = 0; i < 3; i++) {long ugly = factors[i] * min;if(!queue.contains(ugly)) {//去重queue.offer(ugly);}}n--;}}}
思路及总结
利用优先队列进行排序,然后将2、3、5中最小值作为下次相乘的因子,确保没有重复的数字,queue.poll()取得的是即是第 1\2\3\4\5。。。 个数,当n = 1 时,min即是第n个数.
