首页 > 代码库 > Majority Element
Majority Element
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.
第一种解法:O(N)复杂度
class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
d = {}
for i in num:
if d.has_key(repr(i)):
d[repr(i)] = d[repr(i)] + 1
else:
d[repr(i)] = 1;
maxIndex = ‘‘
maxValue = http://www.mamicode.com/0
for key, value in d.items():
if value > maxValue:
maxValue = http://www.mamicode.com/value
maxIndex = key
return int(maxIndex)
Majority Element