Tuesday, August 15, 2017

575. Distribute Candies

https://leetcode.com/problems/distribute-candies/description/
Solution 1. use int array for hash
    int distributeCandies(vector<int>& candies) {
        if(candies.empty()) return 0;
        int count = 0;
        int sz = candies.size();
        // when hash[i] = 1, candy type i in candies.
        int hash[200001] = {0};
        for(int i=0; i<sz; i++) {
            if(!hash[candies[i]+100000] ) {
                count++;
                hash[candies[i]+100000] = 1;
            }
        }
        return min(count,sz/2);
    }

Solution 2. use bitset for hash

    int distributeCandies(vector<int>& candies) {
        if(candies.empty()) return 0;
        int count = 0;
        int sz = candies.size();
        // when hash[i] = 1, candy type i in candies.
        bitset<200001> hash;
        for(int i: candies) {
            if(!hash.test(i+100000) ) {
                count++;
                hash.set(i+100000);
            }
        }
        return min(count, sz/2);
    }

No comments:

Post a Comment