LeetCode 题解工作台
不同整数的最少数目
给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。 示例 1: 输入: arr = [5,5,4], k = 1 输出: 1 解释: 移除 1 个 4 ,数组中只剩下 5 一种整数。 示例 2: 输入: arr = [4,3,1,1…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用哈希表 统计数组 中每个整数出现的次数,然后将 中的值按照从小到大的顺序排序,记录在数组 中。 接下来,我们遍历数组 ,对于当前遍历到的每个值 ,我们将 减去 ,如果 $k \lt 0$,则说明我们已经移除了 个元素,此时数组中不同整数的最少数目为 的长度减去当前遍历到的下标 ,直接返回即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。
示例 1:
输入:arr = [5,5,4], k = 1 输出:1 解释:移除 1 个 4 ,数组中只剩下 5 一种整数。
示例 2:
输入:arr = [4,3,1,1,3,3,2], k = 3 输出:2 解释:先移除 4、2 ,然后再移除两个 1 中的任意 1 个或者三个 3 中的任意 1 个,最后剩下 1 和 3 两种整数。
提示:
1 <= arr.length <= 10^51 <= arr[i] <= 10^90 <= k <= arr.length
解题思路
方法一:哈希表 + 排序
我们用哈希表 统计数组 中每个整数出现的次数,然后将 中的值按照从小到大的顺序排序,记录在数组 中。
接下来,我们遍历数组 ,对于当前遍历到的每个值 ,我们将 减去 ,如果 ,则说明我们已经移除了 个元素,此时数组中不同整数的最少数目为 的长度减去当前遍历到的下标 ,直接返回即可。
若遍历结束,说明我们移除了所有的元素,此时数组中不同整数的最少数目为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
cnt = Counter(arr)
for i, v in enumerate(sorted(cnt.values())):
k -= v
if k < 0:
return len(cnt) - i
return 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates proficiency in frequency counting and hash maps.
- question_mark
Approach effectively uses a greedy strategy to minimize the number of unique integers.
- question_mark
Candidate considers time complexity and implements an efficient solution.
常见陷阱
外企场景- error
Not considering the greedy strategy of removing the least frequent elements first.
- error
Incorrectly handling edge cases where k is 0 or the array has only one unique integer.
- error
Failing to optimize the solution and resorting to unnecessary nested loops.
进阶变体
外企场景- arrow_right_alt
What if `k` is equal to the length of the array?
- arrow_right_alt
What if `k` is 0? How does the solution handle that?
- arrow_right_alt
How does the solution scale with a large input size, such as when `arr.length` approaches 100,000?