Skip to content

Latest commit

 

History

History
58 lines (50 loc) · 965 Bytes

2357.使数组中所有元素都等于零.md

File metadata and controls

58 lines (50 loc) · 965 Bytes

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

/*
 * @lc app=leetcode.cn id=2357 lang=typescript
 *
 * [2357] 使数组中所有元素都等于零
 */

// @lc code=start
function minimumOperations(nums: number[]): number {}
// @lc code=end

解法 1: 排序

function minimumOperations(nums: number[]): number {
  nums.sort((a, b) => a - b)
  let res = 0,
    d = 0
  for (const num of nums) {
    if (num > d) {
      res++
      d = num
    }
  }
  return res
}

解法 2: 哈希表

function minimumOperations(nums: number[]): number {
  nums.sort((a, b) => a - b)
  let res = 0,
    d = 0
  for (let num of nums) {
    if (num > d) {
      res++
      d = num
    }
  }
  return res
}

Case

test.each([
  { input: { nums: [1, 5, 0, 3, 5] }, output: 3 },
  { input: { nums: [0] }, output: 0 },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  expect(minimumOperations(nums)).toEqual(output)
})