首页 > 其他分享 >[LeetCode] 2357. Make Array Zero by Subtracting Equal Amounts

[LeetCode] 2357. Make Array Zero by Subtracting Equal Amounts

时间:2023-02-24 01:44:15浏览次数:59  
标签:nums Amounts Make 元素 Equal 最小 减去 operation LeetCode

You are given a non-negative integer array nums. In one operation, you must:

  • Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
  • Subtract x from every positive element in nums.

Return the minimum number of operations to make every element in nums equal to 0.

Example 1:

Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].

Example 2:

Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

使数组中所有元素都等于零。

给你一个非负整数数组 nums 。在一步操作中,你必须:

选出一个正整数 x ,x 需要小于或等于 nums 中 最小 的 非零 元素。
nums 中的每个正整数都减去 x。
返回使 nums 中所有元素都等于 0 需要的 最少 操作数。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/make-array-zero-by-subtracting-equal-amounts
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题不难,如果你按部就班也能做,我这里分享一个最优解。既然每次需要找的是非零的最小元素 x 然后让 nums 中所有元素的出现次数都减去 x,其实就是让你找 input 数组中非零的不同元素的个数。我跑一个例子,比如 [1, 2, 3, 4, 5]。

第一轮,最小元素是 1,减去 1 之后,所有元素变为 [0, 1, 2, 3, 4]

第二轮,最小元素是 1,减去 1 之后,所有元素变为 [0, 0, 1, 2, 3]

第三轮,最小元素是 1,减去 1 之后,所有元素变为 [0, 0, 0, 1, 2]

第四轮,最小元素是 1,减去 1 之后,所有元素变为 [0, 0, 0, 0, 1]

第五轮,最小元素是 1,减去 1 之后,所有元素变为 [0, 0, 0, 0, 0]

一共需要五次操作,其实这个五次操作对应的是原数组中 unique 的元素个数。所以我们只需要用 hashset 统计原数组中不为零的元素有几个即可。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int minimumOperations(int[] nums) {
 3         HashSet<Integer> set = new HashSet<>();
 4         for (int num : nums) {
 5             if (num != 0) {
 6                 set.add(num);
 7             }
 8         }
 9         return set.size();
10     }
11 }

 

LeetCode 题目总结

标签:nums,Amounts,Make,元素,Equal,最小,减去,operation,LeetCode
From: https://www.cnblogs.com/cnoodle/p/17150011.html

相关文章