卖萌的弱渣

I am stupid, I am hungry.

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.

Solution:

维护一个当前的候选众数e 和一个初始为0的计数器 count。遍历数组时,我们看当前的元素x:

  • 如果计数器是0, 我们将候选众数置为 x 并将计数器置为 1
  • elif e==x, count++,
  • else count–
(Majority-Element.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        e = 0
        counter = 0
        for x in nums:
            if counter == 0:
                e = x
                counter += 1
            elif e == x:
                counter += 1
            else:
                counter -= 1
        return e