C++ 3 lines O(n) Time, O(n) Space. (plus another O(nlgn) Time, O(1) Space)


  • 0
    F
    struct Solution {
        int distributeCandies(vector<int>& candies) {
            unordered_set<int> dict;
            for (int i = 0; i < candies.size() && dict.size() < candies.size()/2;  dict.insert(candies[i++]));
            return dict.size();
        }
    };
    
    
    struct Solution {
        int distributeCandies(vector<int>& candies) {
            sort(candies.begin(), candies.end());
            int count = 1;
            for (int i = 1; i < candies.size() && count < candies.size()/2; ++i)
                count += candies[i] != candies[i-1];
            return count;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.