题目描述:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
方法一:计数法
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 1
        temp = nums[0]
        for i in range(1, len(nums)):
            if nums[i] == temp:
                count += 1
            else:
                count -= 1
                if count == 0:
                    temp = nums[i]
                    count = 1
        return temp方法二:哈希表
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        counts = collections.Counter(nums)
        return max(counts, key=counts.get)方法三:排序
由于多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素,排序后下标为⌊ n/2 ⌋ 的元素必为众数。
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[len(nums) // 2]方法四:摩尔投票法
思路:如果我们把众数记为 +1,把其他数记为 -1,将它们全部加起来,显然和大于 0,从结果本身我们可以看出众数比其他数多。
算法:
-  我们维护一个候选众数 candidate和它出现的次数count。初始时candidate可以为任意值,count为0;
-  我们遍历数组 nums 中的所有元素,对于每个元素 x,在判断 x 之前,如果 count 的值为 0,我们先将 x 的值赋予 candidate,随后我们判断 x: 若x与candidate相等,则count+1;否则,count-1
-  在遍历完成后, candidate即为整个数组的众数。
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        candidate = nums[0]
        count = 0
        for x in nums:
            if count == 0:
                candidate = x
            if x == candidate:
                count += 1
            else:
                count -= 1
        return candidate









