LeetCode 题解工作台
数组大小减半
给你一个整数数组 arr 。你可以从中选出一个整数集合,并删除这些整数在数组中的每次出现。 返回 至少 能删除数组中的一半整数的整数集合的最小大小。 示例 1: 输入: arr = [3,3,3,3,5,5,5,2,2,7] 输出: 2 解释: 选择 {3,7} 使得结果数组为 [5,5,5,2,2…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以用哈希表或数组 统计数组 中每个数字出现的次数,然后将 中的数字从大到小排序,从大到小遍历 ,每次遍历将当前数字 加入答案,并将 加上 ,如果 $m \geq \frac{n}{2}$,则返回答案。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 arr。你可以从中选出一个整数集合,并删除这些整数在数组中的每次出现。
返回 至少 能删除数组中的一半整数的整数集合的最小大小。
示例 1:
输入:arr = [3,3,3,3,5,5,5,2,2,7]
输出:2
解释:选择 {3,7} 使得结果数组为 [5,5,5,2,2]、长度为 5(原数组长度的一半)。
大小为 2 的可行集合有 {3,5},{3,2},{5,2}。
选择 {2,7} 是不可行的,它的结果数组为 [3,3,3,3,5,5,5],新数组长度大于原数组的二分之一。
示例 2:
输入:arr = [7,7,7,7,7,7]
输出:1
解释:我们只能选择集合 {7},结果数组为空。
提示:
1 <= arr.length <= 105arr.length为偶数1 <= arr[i] <= 105
解题思路
方法一:计数 + 排序
我们可以用哈希表或数组 统计数组 中每个数字出现的次数,然后将 中的数字从大到小排序,从大到小遍历 ,每次遍历将当前数字 加入答案,并将 加上 ,如果 ,则返回答案。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minSetSize(self, arr: List[int]) -> int:
cnt = Counter(arr)
ans = m = 0
for _, v in cnt.most_common():
m += v
ans += 1
if m * 2 >= len(arr):
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an understanding of greedy algorithms and how to apply them efficiently.
- question_mark
Check if the candidate can prioritize based on frequency counts for optimization.
- question_mark
Evaluate if the candidate avoids unnecessary complexity by focusing on sorting and frequency analysis.
常见陷阱
外企场景- error
Not sorting the frequency list and blindly removing random elements can lead to suboptimal solutions.
- error
Failing to account for cases where only one integer needs removal.
- error
Over-complicating the approach with unnecessary data structures or logic.
进阶变体
外企场景- arrow_right_alt
What if the array has no duplicates? This changes the dynamic of removal.
- arrow_right_alt
What if you need to remove exactly half of the array, not just at least half?
- arrow_right_alt
Consider situations where integers in the array are very large but their counts are small.