An ugly number is a positive integer whose prime factors are limited to 2
, 3
, and 5
.
Given an integer n
, return the nth
ugly number.
Example 1:
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.
Example 2:
Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
1 <= n <= 1690
题目大意:
求第n个丑数,丑数是由2,3,5相乘获得
Heap算法思路(推荐):
Heap
注意事项:
- 与BFS模板一样,visited要在if里面。可以理解为一个数有三条边产生三个新数,所以和BFS模板一样
Python代码:
1 | def nthUglyNumber(self, n: int) -> int: |
算法分析:
时间复杂度为O(nlogn)
,空间复杂度O(n)
.
双指针算法II解题思路:
比较难想,不推荐,但思路可用于其他题如L373。指针的数乘以指向数组的数,此题中指针为p2, p3, p5, 分别代表2, 3, 5, 数组为res数组,每次比较它们的积。
注意事项:
- 与上题一样要去重,此时,3个乘积中可能会相同且最小,同时移动这些指针
Python代码:
1 | def nthUglyNumber(self, n: int) -> int: |
算法分析:
时间复杂度为O(n)
,空间复杂度O(n)
.