Skip to content

Latest commit

 

History

History
60 lines (53 loc) · 1.47 KB

1224.最大相等频率.md

File metadata and controls

60 lines (53 loc) · 1.47 KB

1224.最大相等频率

/*
 * @lc app=leetcode.cn id=1224 lang=typescript
 *
 * [1224] 最大相等频率
 */

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

解法 1: 哈希表

function maxEqualFreq(nums: number[]): number {
  const map = new Map<number, number>(),
    a = new Map<number, Set<number>>()
  let res = 1
  for (let [len, num] of nums.entries()) {
    if (map.has(num)) {
      const i = map.get(num)!
      a.get(i)!.delete(num)
      if (a.get(i)!.size === 0) a.delete(i)
      map.set(num, i + 1)
    } else {
      map.set(num, 1)
    }
    const i = map.get(num)!
    if (!a.has(i)) a.set(i, new Set())
    a.get(i)!.add(num)
    if (a.size === 1) {
      const [x] = [...a.entries()]
      if (x[0] === 1 || x[1].size === 1) res = Math.max(res, len + 1)
    } else if (a.size === 2) {
      let [x, y] = [...a.entries()]
      if (x[0] > y[0]) [x, y] = [y, x]
      if ((y[0] - x[0] === 1 && y[1].size === 1) || (x[0] === 1 && x[1].size === 1)) res = Math.max(res, len + 1)
    }
  }

  return res
}

Case

test.each([
  { input: { nums: [1, 1] }, output: 2 },
  { input: { nums: [1, 2] }, output: 2 },
  { input: { nums: [1, 1, 1, 2, 2, 2] }, output: 5 },
  { input: { nums: [2, 2, 1, 1, 5, 3, 3, 5] }, output: 7 },
  { input: { nums: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5] }, output: 13 },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  expect(maxEqualFreq(nums)).toEqual(output)
})