575. Distribute Candies 平均分糖果,但要求种类最多

时间:2021-04-27 06:16:08

[抄题]:

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.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

575. Distribute Candies 平均分糖果,但要求种类最多

[一刷]:

  1. 查看set中有几个数,只要用.size()即可

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

hashtable hashset的key都具有单一性 不能重复

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

hashset的key具有单一性 不能重复,对应糖果的种类也是

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

class Solution {
public int distributeCandies(int[] candies) {
//cc
if (candies == null || candies.length == 0) {
return 0;
} //ini
Set kinds = new HashSet(); //for
for (int candy : candies) {
kinds.add(candy);
} //return :
return (candies.length / 2) > kinds.size() ? kinds.size() : (candies.length / 2);
}
}