LeetCode 题解工作台
俄罗斯套娃信封问题
给你一个二维整数数组 envelopes ,其中 envelopes[i] = [w i , h i ] ,表示第 i 个信封的宽度和高度。 当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。 请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(…
4
题型
4
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
时间复杂度 O(nlogn)。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。
当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
注意:不允许旋转信封。
示例 1:
输入:envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出:3
解释:最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
示例 2:
输入:envelopes = [[1,1],[1,1],[1,1]] 输出:1
提示:
1 <= envelopes.length <= 105envelopes[i].length == 21 <= wi, hi <= 105
解题思路
方法一:贪心 + 二分查找
时间复杂度 O(nlogn)。
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x: (x[0], -x[1]))
d = [envelopes[0][1]]
for _, h in envelopes[1:]:
if h > d[-1]:
d.append(h)
else:
idx = bisect_left(d, h)
d[idx] = h
return len(d)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for clear understanding of dynamic programming and binary search usage together.
- question_mark
Assess the candidate's ability to explain how sorting impacts the overall approach.
- question_mark
Check for familiarity with state transitions in dynamic programming problems.
常见陷阱
外企场景- error
Failing to sort the envelopes correctly, especially handling ties in width by sorting in descending order of height.
- error
Overcomplicating the problem by trying to use brute force to compare all pairs of envelopes.
- error
Misunderstanding the role of binary search in the dynamic programming step, potentially leading to inefficient solutions.
进阶变体
外企场景- arrow_right_alt
What if envelopes have more than two dimensions?
- arrow_right_alt
What if the envelopes are in a randomized order with no restrictions?
- arrow_right_alt
Can the approach be optimized further for lower space complexity?