LeetCode Distribute Candies 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. Example 1:
Input: candies = [1,1,2,2,3,3] Output: 3 Explanation: There are three different kinds of candies (1, 2 and 3), and two candies for each kind. Optimal distribution: The sister has candies [1,2,3] and the 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] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.Note:
- The length of the given array is in range [2, 10,000], and will be even.
- The number in given array is in range [-100,000, 100,000].
分糖果问题。给定一个糖果数组,不同数字表示不同种糖果,同一种糖果可能有多个。现在要把这些糖果等数量的分给哥哥和妹妹,问妹妹最多能分到多少种类型的糖果。 简单题,把所有糖果hash一下,看看一共有多少种类型的糖果,如果糖果类型数超过一半,则可以把所有不同类型的糖果拿出来给妹妹,则妹妹得到的糖果类型最多,是n/2。否则有多少种类型的糖果,妹妹最多也只能得到多少中类型的糖果。 代码如下: [cpp] class Solution { public: int distributeCandies(vector<int>& candies) { int n = candies.size(); unordered_map<int, int> table; for (int i = 0; i < n; ++i)++table[candies[i]]; if (table.size() >= n / 2)return n / 2; else return table.size(); } }; [/cpp] 本代码提交AC,用时282MS。]]>