剑指 Offer 39. 数组中出现次数超过一半的数字

题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字  简单 

方法一:哈希表  时间复杂度O(n)  空间复杂度O(n) 

def majorityElement(nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dic = {}
        for num in nums:
            if num in dic:
                dic[num] += 1
            else:
                dic[num] = 1
        
        count = 0
        res = None
        for num in dic:
            if dic[num] > count:
                count = dic[num]
                res = num
        return res

方法二:排序  时间复杂度O(nlogn)  空间复杂度O(1) 

因为题中说有一个数字超过一半,那么排序后数组中点一定为那个数

def majorityElement(nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[len(nums)>>1]

方法三:摩尔投票  时间复杂度O(n)  空间复杂度O(1) 

本题找的数是出现次数超过一半的数,故采用投票法,类似擂台战,上来一个数,如果下一个数和他相同,那么他就加一票,反之则相抵,最后剩下的就是所求

def majorityElement(nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        votes = 0
        for num in nums:
            if votes = 0:
                x = num
            votes += 1 if x == num else -1
        return x
posted @ 2022-07-27 16:04  Liang-ml  阅读(20)  评论(0)    收藏  举报