class(object): defmajorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ if len(nums)==1: return nums ans = [0, 0] cnt = [0, 0] for i in range(len(nums)): match = False for j in range(2): if ans[j]==nums[i]: match = True cnt[j] += 1 break if match: continue full = True for j in range(2): if cnt[j]==0 : ans[j] = nums[i] cnt[j] += 1 full = False break match = False if full: for j in range(2): if nums[i]==ans[j]: cnt[j] += 1 match = True ifnot match: cnt[0] -= 1 cnt[1] -= 1 res = [ans[i] for i in range(2) if cnt[i]>0] cnt = [0]*len(res) if len(res)>0: for n in nums: for j in range(len(res)): if n==res[j]: cnt[j] += 1 return [res[i] for i in range(len(cnt)) if cnt[i]>len(nums)/3]
近期评论