題目Description:###
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:####
找出candies[]中有多少種不同的糖果。
當(dāng) 種類(lèi)數(shù)x<=糖果總數(shù)1/2 時(shí)该编,姐姐最多能拿到x種糖果迄本;
當(dāng) 種類(lèi)數(shù)x>糖果總數(shù)1/2 時(shí),姐姐最多能拿到 糖果總數(shù)*1/2 種糖果课竣;
class Solution(object):
def distributeCandies(self, candies):
sister = []
brother = []
sister.append(candies[0])
for x in candies:
if x not in sister:
sister.append(x)
if len(sister) == len(candies)/2 | len(sister) < len(candies)/2:
return len(sister)
else:
return len(candies)/2
結(jié)果:Time Limit Exceeded
思路2:####
思路1超時(shí)嘉赎,故在思路1的基礎(chǔ)上優(yōu)化;
不需要計(jì)算出candies的種類(lèi),因?yàn)榻憬阕疃嘀荒苣玫絚andies種類(lèi)的一半于樟,一旦種類(lèi)數(shù)計(jì)算達(dá)到一半就不用再計(jì)算了公条。
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
sister = []
sister.append(candies[0])
for x in candies:
if x not in sister and len(sister)< len(candies)/2:
sister.append(x)
return len(sister)
結(jié)果:還是 Time Limit Exceeded
思路3###
參考discuss中[awice]的答案。
其實(shí)就是使用 set()去重
發(fā)現(xiàn)自己根本忘了set()
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
return min(len(candies)/2, len(set(candies)))
結(jié)果:accepted