leetcode575——Distribute Candies

题目大意:给出偶数个元素的数组,每种数字代表一种糖果,现在将糖果均等分给弟弟妹妹,问妹妹最多得到多少种糖果

分析:哈希表的应用。或者直接排序遍历也可以。思路就是如果糖果种类超过总数的一半,则妹妹的糖果种类数就是种数的一半,否则妹妹能得到所有种类的糖果。

代码:

方法一:排序遍历

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值