LeetCode 题解工作台

超过阈值的最少操作数 I

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。 一次操作中,你可以删除 nums 中的最小元素。 你需要使数组中的所有元素都大于或等于 k ,请你返回需要的 最少 操作次数。 示例 1: 输入: nums = [2,11,10,1,3], k = 10 输出: 3 解释: 第一次操…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们只需要遍历一遍数组,统计小于 的元素个数即可。 时间复杂度 ,其中 为数组长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 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 <= 50
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109
  • 输入保证至少有一个满足 nums[i] >= k 的下标 i 存在。
lightbulb

解题思路

方法一:遍历计数

我们只需要遍历一遍数组,统计小于 kk 的元素个数即可。

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        return sum(x < k for x in nums)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

超过阈值的最少操作数 I题解:数组·driven | LeetCode #3065 简单