题目描述:给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
链接:https://leetcode-cn.com/problems/distribute-candies
思路:
1、妹妹和弟弟糖果数要一样,即数组长度的一半
2、糖果种类数不可能超过糖果数,即最大糖果种类数只能是糖果数
3、妹妹获得的糖果种类最多
用哈希表统计糖果种类,计算出糖果种类数和糖果总数的一半,返回两个中的最小值
class Solution {
//妹妹和弟弟糖果数要一样,即数组长度的一半
//糖果种类数不可能超过糖果数,即最大糖果种类数只能是糖果数
//妹妹获得的糖果种类最多
public int distributeCandies(int[] candyType) {
HashMap<Integer,Integer> set = new HashMap<>();
for(int i = 0;i<candyType.length;i++)
{
if(set.containsKey(candyType[i]))
{
set.put(candyType[i],set.get(candyType[i])+1);
}
else{
set.put(candyType[i],1);
}
}
return Math.min(set.size(), candyType.length / 2);
}
}