【leetcode】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].
解析
分糖
给一个数组,这个数组有偶数个,要均分给弟弟和妹妹两人
数组的每一个元素代表一颗糖,元素的一种值代表一种糖
求分给妹妹最多多少种糖
思路
要给妹妹分最多的糖,但妹妹只能拿一半个数的糖,所以如果糖的种数大于半数,则妹妹最多拿半数种类的糖
否则拿所有种类的糖,不够半数的其他糖种类也不会增加
我的解法
我的解法已经比较简单了,但是存在重复计算,忽略了Math.min这个方法
public static int distributeCandies(int[] candies) {
return Arrays.stream(candies).distinct().count() > candies.length / 2 ? candies.length / 2 : (int)
Arrays.stream(candies).distinct().count();
}
最优解
在leetcode上看到一种解法,也是一行,也用了java8新特性,但是他求糖的种类实现比较麻烦,如下
public int distributeCandies(int[] candies) {
return Math.min(candies.length / 2, IntStream.of(candies).boxed().collect(Collectors.toSet()).size());
}
所以最优解可以结合一下(其实后面有人提交了一样的解法)
public static int distributeCandiesOptimize(int[] candies) {
return Math.min(candies.length / 2, (int) IntStream.of(candies).distinct().count());
}