LeetCode 575. Distribute Candies

题意:给一个偶数长数组,每种数字代表一种糖果,两人平分。问一人最多获得几种糖果?

solution 1:hash。见注释

solution 2:bitset。用bitset模拟hash。省去了相对复杂的hash运算,位运算的效率极高。

note:其实思路都是一致的,只是实现的方式不同。在应用中自然是约高效越好,但是在都能满足需求的前提下,我认为使用自己熟悉的方法更合适、更稳妥。

class Solution {
public:
    int distributeCandies(vector<int>& candies) {
        // 1. hash. 一共有 k 种糖果, n = candies.size() 个糖果,每人获得n/2的糖果,返回MIN(K, N/2)
        /*unordered_map<int, int> hash;
        int n = candies.size();
        int k = 0;
        for ( auto c : candies ) {
            if ( hash.find(c) == hash.end() ) {
                hash[c]++;
                k++;
            }
        }
        return ( k < n/2 ) ? k : n/2;*/
        // 2. bitset
        bitset<200001> b;
        int count = 0;
        int n = candies.size();
        for ( auto c : candies ) {
            if ( !b.test( c + 100000 ) ) {
                b.set( c + 100000 );
                count++;
            }
        }
        return min(count, n/2);
    }
};

submission:

1. hash


2. bitset


猜你喜欢

转载自blog.csdn.net/jack_ricky/article/details/79347610