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:

1
2
3
4
5
6
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:

1
2
3
4
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].

解法1:

有一类问题的思路是这样的:如果求最大或者最小值,先考虑一下理论上可能可以取到的值。然后再以此为突破口看看是否有思路。
这题就是这样,先想到要取n/2个数,那么最大的种类也就是n/2,不可能再大了。那么如果数组里的类别比n/2小,那么最大的值就是数组里的数的种类数。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int distributeCandies(int[] candies) {
if (candies == null || candies.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<Integer>();
for (int candy: candies) {
set.add(candy);
}
return Math.min(set.size(), candies.length / 2);
}
}