题目大意:给出偶数个元素的数组,每种数字代表一种糖果,现在将糖果均等分给弟弟妹妹,问妹妹最多得到多少种糖果
分析:哈希表的应用。或者直接排序遍历也可以。思路就是如果糖果种类超过总数的一半,则妹妹的糖果种类数就是种数的一半,否则妹妹能得到所有种类的糖果。
代码:
方法一:排序遍历
class Solution {
public:
int distributeCandies(vector<int>& candies) {
sort(candies.begin(), candies.end());
int ans = 1;
for (int i = 1;i < candies.size();i++) {
if (ans == candies.size() / 2)
break;
if (candies[i] != candies[i - 1]) {
ans++;
}
}
return ans;
}
};
方法二:哈希表 转载自http://blog.csdn.net/whl_program/article/details/71367997
#include <vector>
#include <unordered_map>
int distributeCandies(vector<int>& candies) {
if(candies.size()%2 != 0)
return 0;
unordered_map<int, int> HASH;
int res = 0;
for(int c: candies){
HASH[c]++;
if(HASH[c]==1 && res<candies.size()/2)
res++;
}
return res;
}