575. Distribute Candies

这个题核心思想是找出总共的不同种类的糖数。妹妹能得到的最大不同种类数=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 };

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9140608.html