返回介绍

solution / 3000-3099 / 3065.Minimum Operations to Exceed Threshold Value I / README_EN

发布于 2024-06-17 01:02:57 字数 3616 浏览 0 评论 0 收藏 0

3065. Minimum Operations to Exceed Threshold Value I

中文文档

Description

You are given a 0-indexed integer array nums, and an integer k.

In one operation, you can remove one occurrence of the smallest element of nums.

Return _the minimum number of operations needed so that all elements of the array are greater than or equal to_ k.

 

Example 1:

Input: nums = [2,11,10,1,3], k = 10
Output: 3
Explanation: After one operation, nums becomes equal to [2, 11, 10, 3].
After two operations, nums becomes equal to [11, 10, 3].
After three operations, nums becomes equal to [11, 10].
At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
It can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.

Example 2:

Input: nums = [1,1,2,4,9], k = 1
Output: 0
Explanation: All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.

Example 3:

Input: nums = [1,1,2,4,9], k = 9
Output: 4
Explanation: only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.

 

Constraints:

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109
  • The input is generated such that there is at least one index i such that nums[i] >= k.

Solutions

Solution 1: Traversal and Counting

We only need to traverse the array once, counting the number of elements less than $k$.

The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.

class Solution:
  def minOperations(self, nums: List[int], k: int) -> int:
    return sum(x < k for x in nums)
class Solution {
  public int minOperations(int[] nums, int k) {
    int ans = 0;
    for (int x : nums) {
      if (x < k) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int minOperations(vector<int>& nums, int k) {
    int ans = 0;
    for (int x : nums) {
      if (x < k) {
        ++ans;
      }
    }
    return ans;
  }
};
func minOperations(nums []int, k int) (ans int) {
  for _, x := range nums {
    if x < k {
      ans++
    }
  }
  return
}
function minOperations(nums: number[], k: number): number {
  return nums.filter(x => x < k).length;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文