Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:2357. 使数组中所有元素都等于零,哈希表,详细注释 #481

Open
chencl1986 opened this issue Oct 24, 2024 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/make-array-zero-by-subtracting-equal-amounts/

解题思路:

  1. 仔细观察题目的示例:
输入:nums = [1,5,0,3,5]
输出:3
解释:
第一步操作:选出 x = 1 ,之后 nums = [0,4,0,2,4] 。
第二步操作:选出 x = 2 ,之后 nums = [0,2,0,0,2] 。
第三步操作:选出 x = 2 ,之后 nums = [0,0,0,0,0] 。
  1. 可以发现每个非零数字135,无论个数多少都只做了一次减法
  2. 因此,我们只需要统计nums中一共有多少种非零数字
  3. 也就是说需要统计并去重,因此可以使用Set统计
/**
 * @param {number[]} nums
 * @return {number}
 */
var minimumOperations = function (nums) {
  let set = new Set()

  for (const num of nums) {
    // 每个非零数字都只会减一次,因此只需要用Set统计即可
    num > 0 && set.add(num)
  }

  return set.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant