码迷,mamicode.com
首页 > 其他好文 > 详细

Majority Element

时间:2014-12-29 21:11:57      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

Majority Element

标签:

原文地址:http://www.cnblogs.com/hechengzhu/p/4192312.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!