Skip to content

Latest commit

 

History

History
46 lines (37 loc) · 946 Bytes

575.分糖果.md

File metadata and controls

46 lines (37 loc) · 946 Bytes

575.分糖果

/*
 * @lc app=leetcode.cn id=575 lang=typescript
 *
 * [575] 分糖果
 */

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

解法 1: 贪心

统计所有不同的糖果种类数,然后与 candies.length/2 对比取小者

function distributeCandies(candies: number[]): number {
  const cache = new Set<number>()
  for (const candy of candies) {
    if (!cache.has(candy)) cache.add(candy)
  }
  return Math.min(cache.size, candies.length / 2)
}

一行

function distributeCandies(candies: number[]): number {
  return Math.min(candies.length / 2, new Set(candies).size)
}

Case

test.each([
  { input: { candies: [1, 1, 2, 2, 3, 3] }, output: 3 },
  { input: { candies: [1, 1, 2, 3] }, output: 2 },
])('input:  candies = $input. candies', ({ input: { candies }, output }) => {
  expect(distributeCandies(candies)).toEqual(output)
})