leetcode打卡——去重之575. 分糖果

题目

题目解析

看完题目很快想到先计数出种类个数,然后直接可以得出答案了。。

那么计数的方式最快的当然是哈希。

而哈希中最快的当然是原生数组哈希,由于给出了数据范围,所以可以直接用原生数组哈希!

关于原生数组哈希,就不得不提一嘴bitset,具体使用的文档在这里:bitset文档

解题代码

unordered_set法

class Solution {
    
    
public:
    int distributeCandies(vector<int>& candyType) {
    
    
        int sz = candyType.size();
        unordered_set<int>t(begin(candyType),end(candyType));
        int cnt = t.size();
        return 2*cnt>sz?sz/2:cnt;
    }
};

bitset法

这里由于数据范围是-100000~100000所以为了不产生负数,所以+100000。

class Solution {
    
    
public:
    int distributeCandies(vector<int>& candyType) {
    
    
        bitset<200005> s;
        for(int x: candyType) if(!s[x+100000]) s.set(x+100000);
        return min(candyType.size() / 2, s.count());
    }
};

猜你喜欢

转载自blog.csdn.net/m0_50945504/article/details/121079832