LeetCode题目 Distribute Candies详解(JavaScript)
题目描述
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
(给定一个长度为偶数的整数数组,该数组中的不同数字表示不同类型的糖果。每个数字都是对应的一种糖果。你需要把这些糖果均匀地分配给哥哥妹妹。返回妹妹可以得到的糖果种类的最大数目。)
Example 1:
Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3] Output: 2 Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
- The length of the given array is in range [2, 10,000], and will be even.
- The number in given array is in range [-100,000, 100,000].
主要思路:
var distributeCandies = function(candies) {
var noRepeat = [];
for(var i = 0; i < candies.length; i++){
if(noRepeat.lastIndexOf(candies[i]) == -1){
noRepeat.push(candies[i]);
}
}
if (candies.length / 2 > noRepeat.length) {
return noRepeat.length;
}else {
return candies.length / 2;
}
}
然后提交,提示Time Limit Exceed 超时,我所用的去重方法是最简单但最耗时的一种方法,于是有了下面这种用空间换时间的去重方法,主要思路是新建一js对象以及新数组,遍历传入数组时,判断值是否为js对象的键,不是的话给对象新增该键并放入新数组
var distributeCandies = function(candies) {
var noRepeat = unique(candies)
if (candies.length / 2 > noRepeat.length) {
return noRepeat.length;
}else {
return candies.length / 2;
}
};
function unique(array){
var n = {}, r = [], len = array.length, val, type;
for (var i = 0; i < array.length; i++) {
val = array[i];
type = typeof val;
if (!n[val]) {
n[val] = [type];
r.push(val);
} else if (n[val].indexOf(type) < 0) {
n[val].push(type);
r.push(val);
}
}
return r;
}
var distributeCandies = function(candies) {
return Math.min(new Set(candies).size, candies.length / 2);
};
Set
对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。
语法
new Set([iterable]);
参数
-
iterable
- 如果传递一个 可迭代对象,它的所有元素将被添加到新的 Set中。如果不指定此参数或其值为null,则新的 Set为空。
返回值
一个新的Set对象。
简述
Set
对象是值的集合,你可以按照插入的顺序迭代它的元素。 Set中的元素只会出现一次,即 Set 中的元素是唯一的。
值的相等
因为 Set 中的值总是唯一的,所以需要判断两个值是否相等。判断相等的算法与严格相等(===操作符)不同。具体来说,对于 Set , +0 (+0 严格相等于-0)和-0是不同的值。尽管在最新的 ECMAScript 6规范中这点已被更改。从Gecko 29.0和 recent nightly Chrome开始,Set 视 +0 和 -0 为相同的值。另外,NaN
和undefined
都可以被存储在Set 中, NaN
之间被视为相同的值(尽管 NaN !== NaN)。
| |
| |
| |
| |
|
|