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 …

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

初始时,将第一个丑数 加入堆。每次取出堆顶元素 ,由于 , , 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 去重。 时间复杂度 $O(n \times \log n)$,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,请你找出并返回第 n丑数

丑数 就是质因子只包含 23 和 5 的正整数。

 

示例 1:

输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。

示例 2:

输入:n = 1
输出:1
解释:1 通常被视为丑数。

 

提示:

  • 1 <= n <= 1690
lightbulb

解题思路

方法一:优先队列(最小堆)

初始时,将第一个丑数 11 加入堆。每次取出堆顶元素 xx,由于 2x2x, 3x3x, 5x5x 也是丑数,因此将它们加入堆中。为了避免重复元素,可以用哈希表 visvis 去重。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

丑数 II题解:状态·转移·动态规划 | LeetCode #264 中等