【leetcode】575. 分糖果(js实现)

1. 题目

575. 分糖果
在这里插入图片描述

2. 思路

  1. 先计算出n/2和糖果的类型(通过set对数组去重然后计算数组的长度)
  2. 如果糖果类型个数少于或等于n/2,那就说明糖果不够吃,返回糖果类型的个数
  3. 反之,虽然糖果够吃但是吃不了那么多次,就返回能吃的最大次数…

3. 代码实现

/**
 * @param {number[]} candyType
 * @return {number}
 */
var distributeCandies = function(candyType) {
    
    
    const n_half = candyType.length / 2
    let typeCnt = [...new Set(candyType)].length
    if (n_half >= typeCnt) return typeCnt
    if (n_half < typeCnt) return n_half
};

猜你喜欢

转载自blog.csdn.net/weixin_44109827/article/details/129356026