0%

distribute-candies

Distribute Candies – LeetCode 575

Problem

Description

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Answer

Original

Code

1
2
3
4
5
6
7
class Solution {
public:
int distributeCandies(vector<int>& candies) {
unordered_set<int> m(candies.begin(), candies.end());
return min(m.size(), candies.size() / 2);
}
};

思路

贪心,尽可能的把多的种类一样放一个。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$164$ ms,排名$16.19\%$

Better

思路

还没想到更好的思路。