leetcode系列-多数元素(看到这个题解,我都惊呆了系列)

分类:array

算法:Boyer-Moore 算法

  1. 多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

题解

维护一个计数,遇到多数元素+1,否则减1,这样最后的的计数一定是正的。在遍历数组过程中,遇到清零之后,就重新以当前数字作为候选值,重新开始计算。

代码

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # Boyer-Moore 算法
        candi = nums[0]
        count = 0
        for i in nums:
            if count==0:
                candi=i
            count += (1 if i==candi else -1)
        return candi
发布了26 篇原创文章 · 获赞 0 · 访问量 5404

猜你喜欢

转载自blog.csdn.net/Yolo_C/article/details/104750247