575. Distribute Candies

本文探讨了糖果分配问题的两种解决方案:一种是通过排序并统计不同类型的糖果数量;另一种则是利用bitset来高效地记录每种类型的糖果,最终确定妹妹能获得的最大不同种类糖果数。

这个题核心思想是找出总共的不同种类的糖数。妹妹能得到的最大不同种类数=min(count,sz/2)

方法一,排序,扫描,然后用计数器对不同种类数计数运行时间135ms

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int distributeCandies(vector<int>& candies) 
12     {
13         sort(candies.begin(),candies.end());
14         int sz=candies.size();
15         int count=1;
16         for(int i=1;i<sz;i++)
17         {
18             if(candies[i]!=candies[i-1])
19                 count++;
20         }
21         return min(count,sz/2);
22     }
23 };

方法二,用bitset来统计

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int distributeCandies(vector<int>& candies) 
12     {
13         bitset<200001> s;
14         size_t count=0;
15         for(int i:candies)
16         {
17             count+=!s.test(i+100000);
18             s.set(i+100000);
19         }
20         return min(count,candies.size()/2);
21     }
22 };

 

转载于:https://www.cnblogs.com/zhuangbijingdeboke/p/9140608.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值