575. Distribute Candies
575. 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].
题目大意:
有一个int[] 数组表示糖果,每一种不同的数字表示糖果的种类。其中糖果的个数一定是偶数个。
现在要将这些糖果平均分给哥哥和妹妹,哥哥和妹妹各获得一半。
希望妹妹能分到更多种类的糖果,要求输出妹妹最多能获得的糖果的种类数。
思路:
先排序,再遍历整个数组,获得所有糖果中糖果的种类数
其中,如果种类数大于所有数量的1/2,则妹妹只能获得所有数量的1/2种糖果;
如果种类数小于所有数量的1/2,则妹妹最多只能获得种类数
class Solution { public int distributeCandies(int[] candies) { //int[] candies = {1,1,1,1,3,3}; Arrays.sort(candies); int temp = candies[0]; int count = 1; for (int i = 0; i < candies.length; i++) { if(temp!=candies[i]){ count++; temp = candies[i]; } } if(count>candies.length/2) return candies.length/2; else return count; } }