题目: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.
意思大概就是两兄妹分糖果,给一个数组,一个数字代表一种糖果,平均分,问最多能分到几种糖果
思路:刚开始想的太复杂,理不清那种,后面仔细看了以下题目,其实很简单,就是如果数组的长度的一半超过糖果的种类,那就是重复的有很多,可以分到全部的种类,如果数组的长度的一般没有超过糖果的种类,说明重复的少,只要返回数组长度的一半就可以了,用hashset解决计算糖果种类。
代码:
public int distributeCandies(int[] candies) {
if(candies.length==0)return 0;
HashSet a=new HashSet();
for(int i=0;i<candies.length;i++){
a.add(candies[i]);
}
if(a.size()>candies.length/2){
return candies.length/2;
}else{
return a.size();
}
}
看了以下solution和我的基本一样,也是用hashset来算糖果种类
public int distributeCandies(int[] candies) {
Set<Integer> kinds = new HashSet<>();
for (int candy : candies) kinds.add(candy);
return kinds.size() >= candies.length / 2 ? candies.length / 2 : kinds.size();
}