169 Majority element

PPZ發表於2015-02-16

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.

還是來備註一些,因為過後自己都看不懂了,還好後面有演算法發明人的演示。 演算法大意是:從第一個數開始記為1,然後向後遍歷,遇到不同的就減1,相同的就加1,變成0以後把下一個數變成candidate.

class Solution:
# @param num, a list of integers
# @return an integer
def majorityElement(self, num):
   candidate = 0
   count = 0
   for value in num:
       if count == 0:
           candidate = value
       if candidate == value:
           count +=1
       else:
           count -=1
   return candidate

http://gregable.com/2013/10/majority-vote-algorithm-find-majority.html
演示: http://www.cs.utexas.edu/~moore/best-ideas/mjrty/example.html

相關文章