categories: leetcode


carbon.png

题目描述

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

  1. is the sequence of the first

10

  1. ugly numbers.**Note: **
  2. 1. `1` is typically treated as an ugly number.
  3. 1. `n` **does not exceed 1690**.
  4. <a name="36967e2c"></a>
  5. ## 参考代码
  6. ```java
  7. class Solution {
  8. public int nthUglyNumber(int n) {
  9. int factors[] = {2,3,5};
  10. //优先队列
  11. Queue<Long> queue = new PriorityQueue<>();
  12. queue.offer(1L);
  13. 注意第1690个可能会超过int的范围
  14. while (true) {
  15. long min = queue.poll();//每次取最小值相乘,取得第n个数
  16. if (n == 1) {
  17. return (int)min;
  18. }
  19. for (int i = 0; i < 3; i++) {
  20. long ugly = factors[i] * min;
  21. if(!queue.contains(ugly)) {//去重
  22. queue.offer(ugly);
  23. }
  24. }
  25. n--;
  26. }
  27. }
  28. }

思路及总结

利用优先队列进行排序,然后将2、3、5中最小值作为下次相乘的因子,确保没有重复的数字,queue.poll()取得的是即是第 1\2\3\4\5。。。 个数,当n = 1 时,min即是第n个数.

参考

https://chuansongme.com/n/1648591652025