LeetCode:Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊
n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
解决思路:
找到不同的两个元素之后就同时“删除”这两个元素,最后剩下的哪个就是majority element
我用python 做的:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result =0
counter = 0
for i in nums:
if counter ==0:
result = i
counter =1
elif i ==result:
counter+=1
else :
counter-=1
return result