Skip to content

Latest commit

 

History

History
49 lines (43 loc) · 978 Bytes

2404.出现最频繁的偶数元素.md

File metadata and controls

49 lines (43 loc) · 978 Bytes

2404.出现最频繁的偶数元素

/*
 * @lc app=leetcode.cn id=2404 lang=typescript
 *
 * [2404] 出现最频繁的偶数元素
 */

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

解法 1: 哈希表

function mostFrequentEven(nums: number[]): number {
  const map = new Map<number, number>()
  for (let num of nums) {
    if (num % 2 === 0) {
      map.set(num, (map.get(num) ?? 0) + 1)
    }
  }
  let res = -1,
    max = 0
  for (let [a, b] of map) {
    if (b > max) {
      res = a
      max = b
    } else if (b === max && a < res) {
      res = a
    }
  }
  return res
}

Case

test.each([
  { input: { nums: [0, 1, 2, 2, 4, 4, 1] }, output: 2 },
  { input: { nums: [4, 4, 4, 9, 2, 4] }, output: 4 },
  { input: { nums: [29, 47, 21, 41, 13, 37, 25, 7] }, output: -1 },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  expect(mostFrequentEven(nums)).toEqual(output)
})