575.分巧克力(javascript)575.DistributeCandies
原创Alice 有 n 糖,其中第一种 i 糖的类型是 candyType[i] 。Alice 注意到她体重增加,她去看医生了。
医生建议 Alice 少吃糖,只吃她所有的糖 n / 2 即可(n 是偶数)。Alice 她非常喜欢这些糖。她想在医生的建议下吃尽可能多的不同种类的糖。
给你一个长度 n 整数数组 candyType ,返回: Alice 在仅吃掉 n / 2 如果是糖,你可以吃糖 最多 种类数。
Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor’s advice.
Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.
示例 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
发现 有两种吃的最多
1.candyType长度的一半
2.过滤掉重复元素的数组长度
两种情况都选择最小的一个,因为两种情况是一致的。
var distributeCandies = function (candyType) {
let len = candyType.length
let max = len / 2
let newList = array_deduplication(candyType)
return Math.min(max, newList.length)
};
function array_deduplication(arr) {
return arr.filter(function (c, index) {
return arr.indexOf(c) === index;
});
}
代码优化,但执行时间过长。
var distributeCandies = function (candyType) {
let newList = candyType.filter(function (c, index) {
return candyType.indexOf(c) === index;
});
return Math.min(candyType.length / 2, newList.length)
};
采用es6筛选重复项
var distributeCandies = function (candyType) {
let newSet = new Set(candyType)
return Math.min(candyType.length / 2, newSet.size)
};
leetcode: https://leetcode.cn/problems/distribute-candies/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123


