给定长度为偶数的整数数组,该数组中不同的数字代表不同种类的糖果, 每个数字表示一种糖果。 您需要将这些糖果平均分配给弟弟和妹妹。 返回妹妹可以获得的糖果种类的最大数量。
样例
输入: candies = [1,1,2,2,3,3]
输出: 3
解释:
有三种不同的糖果(1, 2 and 3), 每种糖果有两个。
最佳分法:妹妹拥有[1,2,3] ,弟弟也会拥有拥有[1,2,3]。
妹妹拥有3种不同的糖果。
注意事项
所给数组的长度范围为[2, 10,000],且为偶数。
所给数组中数字的范围为[-100,000, 100,000]。
解题思路:
非常简单。见注释
public class Solution {
/**
* @param candies: a list of integers
* @return: return a integer
*/
public int distributeCandies(int[] candies) {
// write your code here
Map<Integer,Integer> map = new HashMap<>();//key糖果种类,value该种类的数量
for(int candy : candies){
if(map.get(candy) == null)
map.put(candy,1);
else
map.put(candy,1+map.get(candy));
}
int count = candies.length/2;
//如果妹妹应该拿到糖的数量>=糖果种类数,则妹妹最多拿到糖果种类数的种类
//否则最多拿到应该拿到糖的数量
if(count >= map.size())
return map.size();
else
return count;
}
}