46 · 主元素

描述
给定一个整型数组,找出主元素,它在数组中的出现次数大于数组元素个数的二分之一。

You may assume that the array is non-empty and the majority number always exist in the array.

样例
样例 1:

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

输入: [1, 1, 1, 2, 2, 2, 2]
输出: 2
挑战
要求时间复杂度为O(n),空间复杂度为O(1)

class Solution:
    """
    @param: nums: a list of integers
    @return: find a  majority number
    """
    def majorityNumber(self, nums):
        count = 1
        res = nums[0]
        for i in range(1,len(nums)):
            if nums[i] != res:
                count -= 1
                if count<0:
                    count = 1
                    res = nums[i]
            else:
                count += 1
        return res
posted @ 2021-04-20 22:00  bernieloveslife  阅读(48)  评论(0编辑  收藏  举报