leetcode算法:Distribute Candies

时间:2021-05-22 17:12:26
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]. 这道题是说 给我们一个数组 [1,1,2,2,3,3]
每个数字代表一种类型的糖果,这个数组也就是有两颗1类型糖果 两个2类型糖果 两个3类型糖果 现在要男孩和女孩数量上等分这些糖果,问女孩最多能得到多少种类的糖果 思想就是:
num1 = 总数量/2 num2 = 糖果种类数
如果num1 更多,那女孩一定能每种糖果得到一个以上,所以num2是答案
如果num2更大,那么女孩就不可能每种糖果都能拿到一个,所以num1就是答案 总数量就是数组的长度,糖果种类数就是把数组去重,看有多少个数字,可以用集合来做,
我的python代码:
 class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
kinds = len( set(candies) )
nums = len(candies)/2
if kinds< nums:
return kinds
else:
return nums if __name__ == '__main__':
s = Solution()
res = s.distributeCandies([1,1,1,1,2,2,2,3,3,3])
print(res)