2. 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 = 0
    for key, value in d.items():
      if value > maxValue:
        maxValue = value
        maxIndex = key

    return int(maxIndex)

 

posted @ 2014-12-29 19:59  hechengzhu  阅读(120)  评论(1)    收藏  举报