sdtf08 发表于 2015-12-2 13:04:40

leetcode 【 Majority Element 】python 实现

  题目:
  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.
  
  代码:oj测试通过 Runtime: 197 ms



1 class Solution:
2   # @param num, a list of integers
3   # @return an integer
4   def majorityElement(self, num):
5         if len(num) == 1:
6             return num
7         
8         candidate = 0
9         count = 0
10         for i in range(len(num)):
11             if count == 0:
12               candidate = num
13               count += 1
14             else:
15               if num == candidate :
16                     count += 1
17               else:
18                     count -= 1
19         return candidate
  思路:
  这个自己想不出来。上网找的Moore Voting算法。
  这个方法在思路上还是比较朴实无华的,但是很精妙。
  注意题目的条件,重复出现大于数据长度一半的元素为众数。
  因此可以采用一种对冲思路:一旦相邻的两个元素不同,就把这两个元素对冲抵消掉;由于众数的出现频次大于数据其他所有元素出现频次之和,所以这种对冲抵消最后剩下的一定是众数。
  之前看过几篇日志说这道题 还不错 记录在下面:
  http://www.yanyulin.info/pages/2014/12/851338983752.html
  http://www.geeksforgeeks.org/majority-element/
  http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/
页: [1]
查看完整版本: leetcode 【 Majority Element 】python 实现