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.
主元素问题。而且题目假设了主元素一定存在。
如果主元素存在,那么在数组中任一删除两个不同的元素,在剩下的数组中主元素不会发生改变。因此定义两个变量,cur和cnt。cur记录当前正在标记的数据,cnt记录cur出现的次数。如果遍历的数字等于cur那么cnt+=1 否则cnt-=1。cnt等于0的时候重新计算cur。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count, cur = 0, 0
for i in range(len(nums)):
if count == 0:
cur = nums[i]
count = count+1 if nums[i] == cur else count-1
return cur