leetcode229 摩爾投票

169、229

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        count1=0
        count2=0
        cand1=None
        cand2=None
        for i in nums:
            if cand1==i:
                count1+=1
            elif cand2==i:
                count2+=1
            elif count1==0:
                count1=1
                cand1=i
            elif count2==0:
                count2=1
                cand2=i
            else:
                count1-=1
                count2-=1           
        res=[]        
        n=len(nums)
        if nums.count(cand1)>n/3:
            res.append(cand1)
        if nums.count(cand2)>n/3:
            res.append(cand2)
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章