LeetCode1-Distribute Candies-[Easy]

题目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[]中有多少种不同的糖果。
当 种类数x<=糖果总数1/2 时,姐姐最多能拿到x种糖果;
当 种类数x>糖果总数
1/2 时,姐姐最多能拿到 糖果总数*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

结果:Time Limit Exceeded

思路2:####

思路1超时,故在思路1的基础上优化;
不需要计算出candies的种类,因为姐姐最多只能拿到candies种类的一半,一旦种类数计算达到一半就不用再计算了。

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)

结果:还是 Time Limit Exceeded


思路3###

参考discuss中[awice]的答案。
其实就是使用 set()去重
发现自己根本忘了set()


LeetCode1-Distribute Candies-[Easy]_第1张图片
class Solution(object):
    def distributeCandies(self, candies):
        """
        :type candies: List[int]
        :rtype: int
        """
        return min(len(candies)/2, len(set(candies)))

结果:accepted

你可能感兴趣的:(LeetCode1-Distribute Candies-[Easy])