[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.
关键点在于多于⌊ n/2 ⌋次。按特征切分成两半,一定有一边是多于一半的。可以用哈希,但直接统计个数两两相消可以就地解决。
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
cur = 0
count = 0
for i in num:
if(count == 0):
cur = i
count+=1
else:
if(cur == i):
count+=1
else:
count-=1
return cur