js - leetcode-分糖果

183 阅读2分钟

这是我参与2022首次更文挑战的第35天,活动详情查看:2022首次更文挑战

前言

  • 有人相爱,有人夜里开车看海,有人leetcode第一题都做不出来,由此可见,leetcode的题还是有分量的。今天我们就来会会它们

题目地址

分糖果

题目描述

Alice 有 n 枚糖,其中第 i 枚糖的类型为 candyType[i] 。Alice 注意到她的体重正在增长,所以前去拜访了一位医生。

医生建议 Alice 要少摄入糖分,只吃掉她所有糖的 n / 2 即可(n 是一个偶数)。Alice 非常喜欢这些糖,她想要在遵循医生建议的情况下,尽可能吃到最多不同种类的糖。

给你一个长度为 n 的整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 枚糖的情况下,可以吃到糖的 最多 种类数。

示例 1:

输入:candyType = [1,1,2,2,3,3]
输出:3
解释:Alice 只能吃 6 / 2 = 3 枚糖,由于只有 3 种糖,她可以每种吃一枚。

示例 2:

输入:candyType = [1,1,2,3]
输出:2
解释:Alice 只能吃 4 / 2 = 2 枚糖,不管她选择吃的种类是 [1,2][1,3] 还是 [2,3],她只能吃到两种不同类的糖。

示例 3:

输入:candyType = [6,6,6,6]
输出:1
解释:Alice 只能吃 4 / 2 = 2 枚糖,尽管她能吃 2 枚,但只能吃到 1 种糖。

提示:

n == candyType.length
2 <= n <= 104
n 是一个偶数
-105 <= candyType[i] <= 105

贪心算法

思路

  • 因为 candyType 是偶数,所以对其进行 / 2 操作,会得到一个整数,表示 Alice每天吃糖的最大数
  • candyType 执行去重操作, 得到不同糖果的集合
  • 判断 去重后的集合长度是否大于 candyType / 2
    • 大于的话,表示糖果种类大于 candyType的一半,但Alice每天只能吃 candyType / 2的糖果,所以返回 candyType / 2
    • 否则,返回是所有糖类的个数即可

解法一

/**
 * @param {number[]} candyType
 * @return {number}
 */
var distributeCandies = function (candyType) {
    // 首先对数组进行去重操作,得到不同糖果的个数
    const singleListLth = [...new Set(candyType)].length
    // 对所有的糖果进行 / 2 操作,因为 candyType 是偶数,所以不用关心小数问题
    const halfNumberLth = candyType.length / 2
    // 判断, 如果 halfNumberLth - singleListLth > 0 ,
    // 表示不同糖果类型的总数小于,总糖果的一般,直接返回singleListLth即可
    // 否则返回 halfNumberLth (Alice最多只能吃掉 n / 2的糖果)
    return halfNumberLth - singleListLth > 0 ? singleListLth : halfNumberLth
};

解法二

/**
 * @param {number[]} candyType
 * @return {number}
 */
var distributeCandies = function (candyType) {
    return Math.min(new Set(candyType).size, candyType.length / 2);
};

写在最后

  • 希望你能收获满满