哇,这么题!!虽然写的是easy!但是我!!!用了三种方法才过!
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].
思路一:把所有的糖果拼成一个字符串,然后再用indexOf发现重复。
测试通过之后提交。显示超时。。
var distributeCandies = function(candies) {
var candiesStr='';
var candiesTypeCount=0;
var len=candies.length;
for(var i=0;i<len;i++){
if(candiesStr.indexOf(","+candies[i]+",")<0){
candiesTypeCount++;
candiesStr+=(","+candies[i]+",");
}
}
if(candiesTypeCount<candies.length/2){
return candiesTypeCount;
}else{
return candies.length/2;
}
}
换思路,此时百度发现
http://blog.csdn.net/grape875499765/article/details/73496929
他用的散列表。看了一下觉得效率应该很高。
于是如法炮制
var distributeCandies = function(candies) {
var result=0;
var arr=new Array(200002);
for(var i=0;i<candies.length;i++){
if(!arr[candies[i]+100000]){
arr[candies[i]+100000] = true;
result++;
}
}
return result>candies.length/2 ? candies.length/2 : result;
}
心想这次的效率肯定没得说了。。结果提交之后显示使用空间超过限制。
好吧。。
方法三:排序!
var distributeCandies = function(candies) {
var arr=candies.sort(function(a,b){return b-a});
var count = 1;
for(var i=1;i<arr.length;i++){
if(arr[i]!==arr[i-1]){count++;}
}
return count>candies.length/2 ? candies.length/2 : count;
};
终于过了。。
JavaScript中排序默认用的快速排序。整个用了435ms,感觉还是不算很快。
hash是用空间换时间的方法,如果给定糖果范围小一点应该还是不错的。