LeetCode 题解工作台
删除数对后的最小数组长度
给你一个下标从 0 开始的 非递减 整数数组 nums 。 你可以执行以下操作任意次: 选择 两个 下标 i 和 j ,满足 nums[i] 。 将 nums 中下标在 i 和 j 处的元素删除。剩余元素按照原来的顺序组成新的数组,下标也重新从 0 开始编号。 请你返回一个整数,表示执行以上操作任意…
6
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 统计数组 中每个元素的出现次数,然后将 中的每个值加入一个优先队列(大根堆) 中。每次从 中取出两个元素 和 ,将它们的值减一,如果减一后的值仍大于 ,则将减一后的值重新加入 。每次从 中取出两个元素,表示将数组中的两个数对删除,因此数组的长度减少 。当 的大小小于 时,停止删除操作。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的 非递减 整数数组 nums 。
你可以执行以下操作任意次:
- 选择 两个 下标
i和j,满足nums[i] < nums[j]。 - 将
nums中下标在i和j处的元素删除。剩余元素按照原来的顺序组成新的数组,下标也重新从 0 开始编号。
请你返回一个整数,表示执行以上操作任意次后(可以执行 0 次),nums 数组的 最小 数组长度。
示例 1:
输入:nums = [1,2,3,4]
输出:0
解释:

示例 2:
输入:nums = [1,1,2,2,3,3]
输出:0
解释:

示例 3:
输入:nums = [1000000000,1000000000]
输出:2
解释:
由于两个数字相等,不能删除它们。
示例 4:
输入:nums = [2,3,4,4,4]
输出:1
解释:

提示:
1 <= nums.length <= 1051 <= nums[i] <= 109nums是 非递减 数组。
解题思路
方法一:贪心 + 优先队列(大根堆)
我们用一个哈希表 统计数组 中每个元素的出现次数,然后将 中的每个值加入一个优先队列(大根堆) 中。每次从 中取出两个元素 和 ,将它们的值减一,如果减一后的值仍大于 ,则将减一后的值重新加入 。每次从 中取出两个元素,表示将数组中的两个数对删除,因此数组的长度减少 。当 的大小小于 时,停止删除操作。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def minLengthAfterRemovals(self, nums: List[int]) -> int:
cnt = Counter(nums)
pq = [-x for x in cnt.values()]
heapify(pq)
ans = len(nums)
while len(pq) > 1:
x, y = -heappop(pq), -heappop(pq)
x -= 1
y -= 1
if x > 0:
heappush(pq, -x)
if y > 0:
heappush(pq, -y)
ans -= 2
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for efficiency in handling large input arrays (up to 10^5 elements).
- question_mark
Evaluate the candidate's approach to minimizing operations and array length.
- question_mark
Assess their understanding of array scanning and hash lookups in reducing problem complexity.
常见陷阱
外企场景- error
Not considering the sorted nature of the array could lead to unnecessary comparisons.
- error
Failing to efficiently track element frequencies, causing an excessive number of operations.
- error
Overcomplicating the solution by not using hash tables or efficient frequency counting methods.
进阶变体
外企场景- arrow_right_alt
Consider unsorted arrays or arrays with more varied element frequencies.
- arrow_right_alt
Explore variations with constraints on the number of allowed operations.
- arrow_right_alt
What if the array contains only one element or no removable pairs?