LeetCode | 575. Distribute Candies


题外话:又是N久没有更博,今后争取每天总结。奋斗


Leetcode上的新题,难度是Easy,我是按照acceptance刷的,所以经常遇到新题^_________^


题目:

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.

题意解读:

给出偶数长度的一个数组,其中不同的数字代表不同种类的糖果。每个数字代表对应的种类,需要将这些糖果 数量平均 地分给你的哥哥和姐姐(好吧,或者弟弟妹妹)。要求返回姐姐可能获得糖果种类的最大值。


输入范围:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].

思路分析:

1. 1M的内存空间可以支持32位int型数组大小为26万+,所以可以使用int或bool型数组对所有第一次出现的candy种类进行记录,并使用kindnum变量记录不同candy种类数,如果出现过则不修改kindnum。最终根据kindnum大小进行返回操作,若kindnum大于candies长度一半,则sister最多获得candies.size()/2种糖果;若小于,则返回kindnum。

2. 也可以用map数据结构,对每个出现的candy用pair进行记录,每次对整个map数据结构进行find查找,若没有出现过该种类candy,则insert新的pair。最终根据map的元素数量进行返回操作,原理同第一种解法。


下面给出上面两种思路的代码,效率都不是很高,分别199ms和440ms,虽然都是一次AC,但感觉解法还不够优化。欢迎大家的指导和讨论。


第一种解法:

        int distributeCandies(vector<int>& candies) {
        if(candies.size()<1)
			return 0;
		bool kinds[200005] = {0};
		int kindnum = 0;
		for(int i = 0; i<candies.size(); i++){
			int idx = candies[i] + 100000;
			if(!kinds[idx]){
				kinds[idx] = 1;
				kindnum ++;
			}
		}
		if(kindnum >= candies.size()/2)
			return candies.size()/2;
		return kindnum;
    }


第二种解法:

	int distributeCandies(vector<int>& candies) {
        if(candies.size()<1)
			return 0;
		map<int, bool> kinds;
		for(int i = 0; i<candies.size(); i++){
			int kindnum = candies[i];
			map<int, bool>::iterator iter = kinds.find(kindnum);
			if(iter == kinds.end())
				kinds.insert(pair<int,bool>(kindnum,true));
		}
		if(kinds.size()>=candies.size()/2)
			return candies.size()/2;
		else return kinds.size();
    }








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值