Given aninteger array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy ofthe corresponding kind. You need to distribute these candies equally innumberto brother and sister. Return the maximum numberof kinds of candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2and3), andtwo candies foreach kind.
Optimal distribution: The sister has candies [1,2,3] andthe brother has candies [1,2,3], too.
The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] andthe brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.
Note:
The lengthofthe given array is in range [2, 10,000], and will be even.
The numberin given array is in range [-100,000, 100,000].
二、解题:
class Solution {
/*
需要先计算出vector不同数的个数,
因此用unordered_set这个容器很适合。
*/public:
int distributeCandies(vector<int>& candies)
{
unordered_set<int> s1;
for (int i = 0; i < candies.size(); i++)
{
s1.insert(candies[i]);
}
if (s1.size() <= candies.size() / 2)
return s1.size();
elsereturn candies.size() / 2;
}
};