leetcode -- Majority Element II -- 重点

https://leetcode.com/problems/majority-element-ii/

结合https://leetcode.com/problems/majority-element/一起看

这里要用moore voting算法。参考http://www.cnblogs.com/NickyYe/p/4231000.html
http://mabusyao.iteye.com/blog/2223195

思路:可以得到最多有两个这样的majority,因为个数要大于floor(n/3),不是等于。这是一个所谓的摩尔投票算法,可以在线性时间O(n)内解决问题。这也是一个很容易就想到的算法,不过需要总结一下才能写出。类似于不同的元素就抵消,相同的用一个数字计数的思想。基本思想是,用两个变量,candidate存前一个遍历的元素,counter用来计数。从头遍历数组,如果candidate和当前元素相同,candidate不变,counter++。如果candidate和当前元素不同,但是counter>0证明,这个candidate前面已经出现很多次了,那么counter–,抵消一次,直到counter==0。所以如果candidate和当前元素不同,而且counter==0,证明这个candidate已经被抵消了,就当前匀速取代这个candidate。如此往复,遍历整个数组。

这里抵消可以看成机会成本,此消彼长

code用http://bookshadow.com/weblog/2015/06/29/leetcode-majority-element-ii/

class Solution:
    # @param {integer[]} nums
    # @return {integer[]}
    def majorityElement(self, nums):
        n1 = n2 = None
        c1 = c2 = 0
        for num in nums:
            if n1 == num:
                c1 += 1
            elif n2 == num:
                c2 += 1
            elif c1 == 0:
                n1, c1 = num, 1
            elif c2 == 0:
                n2, c2 = num, 1
            else:
                c1, c2 = c1 - 1, c2 - 1
        size = len(nums)
        return [n for n in (n1, n2) 
                   if n is not None and nums.count(n) > size / 3]

你可能感兴趣的:(LeetCode)