题目
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.
求数组中的主要元素:出现次数超过一半的数
python代码
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
major=nums[0]
count = 1
for i in range(1, len(nums)):
if count == 0:
count+=1
major=nums[i]
elif major==nums[i]:
count+=1
else:
count -=1
return major