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[]中有多少種不同的糖果。
當(dāng) 種類數(shù)x<=糖果總數(shù)1/2 時(shí),姐姐最多能拿到x種糖果;
當(dāng) 種類數(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的種類,因?yàn)榻憬阕疃嘀荒苣玫絚andies種類的一半,一旦種類數(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容