LeetCode 题解工作台
丑数 II
给你一个整数 n ,请你找出并返回第 n 个 丑数 。 丑数 就是质因子只包含 2 、 3 和 5 的正整数。 示例 1: 输入: n = 10 输出: 12 解释: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。 示例 2: 输入: n = 1 …
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
初始时,将第一个丑数 加入堆。每次取出堆顶元素 ,由于 , , 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 去重。 时间复杂度 $O(n \times \log n)$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是质因子只包含 2、3 和 5 的正整数。
示例 1:
输入:n = 10 输出:12 解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
示例 2:
输入:n = 1 输出:1 解释:1 通常被视为丑数。
提示:
1 <= n <= 1690
解题思路
方法一:优先队列(最小堆)
初始时,将第一个丑数 加入堆。每次取出堆顶元素 ,由于 , , 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 去重。
时间复杂度 ,空间复杂度 。
class Solution:
def nthUglyNumber(self, n: int) -> int:
h = [1]
vis = {1}
ans = 1
for _ in range(n):
ans = heappop(h)
for v in [2, 3, 5]:
nxt = ans * v
if nxt not in vis:
vis.add(nxt)
heappush(h, nxt)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for familiarity with dynamic programming and heap-based approaches.
- question_mark
Evaluate whether the candidate can optimize space complexity while maintaining time efficiency.
- question_mark
Assess how well the candidate can combine multiple data structures (heap, array) to solve a problem.
常见陷阱
外企场景- error
Failing to optimize the solution by checking each number for ugliness rather than using dynamic programming.
- error
Incorrectly managing the pointers for 2, 3, and 5, which can result in missed ugly numbers.
- error
Using brute force methods that don't leverage the state transition optimization, leading to inefficient solutions.
进阶变体
外企场景- arrow_right_alt
Find the nth ugly number without using a heap, relying purely on dynamic programming.
- arrow_right_alt
Optimize the solution for larger values of n, up to the maximum constraint.
- arrow_right_alt
Extend the concept of ugly numbers to include other primes, such as 7, 11, etc.