LeetCode 题解工作台
超过阈值的最少操作数 I
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。 一次操作中,你可以删除 nums 中的最小元素。 你需要使数组中的所有元素都大于或等于 k ,请你返回需要的 最少 操作次数。 示例 1: 输入: nums = [2,11,10,1,3], k = 10 输出: 3 解释: 第一次操…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们只需要遍历一遍数组,统计小于 的元素个数即可。 时间复杂度 ,其中 为数组长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。
一次操作中,你可以删除 nums 中的最小元素。
你需要使数组中的所有元素都大于或等于 k ,请你返回需要的 最少 操作次数。
示例 1:
输入:nums = [2,11,10,1,3], k = 10 输出:3 解释:第一次操作后,nums 变为 [2, 11, 10, 3] 。 第二次操作后,nums 变为 [11, 10, 3] 。 第三次操作后,nums 变为 [11, 10] 。 此时,数组中的所有元素都大于等于 10 ,所以我们停止操作。 使数组中所有元素都大于等于 10 需要的最少操作次数为 3 。
示例 2:
输入:nums = [1,1,2,4,9], k = 1 输出:0 解释:数组中的所有元素都大于等于 1 ,所以不需要对 nums 做任何操作。
示例 3:
输入:nums = [1,1,2,4,9], k = 9 输出:4 解释:nums 中只有一个元素大于等于 9 ,所以需要执行 4 次操作。
提示:
1 <= nums.length <= 501 <= nums[i] <= 1091 <= k <= 109- 输入保证至少有一个满足
nums[i] >= k的下标i存在。
解题思路
方法一:遍历计数
我们只需要遍历一遍数组,统计小于 的元素个数即可。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(x < k for x in nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Notice that the operation always removes the current minimum, so ask whether simulation is actually necessary.
- question_mark
A strong solution explains why counting num < k is equivalent to counting required deletions.
- question_mark
The key insight is proving that elements already at least k never block the answer for this problem.
常见陷阱
外企场景- error
Sorting the array first adds extra work even though the answer depends only on how many values are below k.
- error
Using <= k instead of < k is wrong because values equal to k already satisfy the threshold.
- error
Simulating removals can hide the simple invariant that every below-threshold element must be deleted exactly once.
进阶变体
外企场景- arrow_right_alt
What changes if the operation can remove any element, not just the smallest, before all values reach k?
- arrow_right_alt
How would the approach differ in Minimum Operations to Exceed Threshold Value II, where elements are combined instead of simply removed?
- arrow_right_alt
What if you had to return the actual removed values in order rather than only the minimum count?