leetcode--python--剑指 Offer 39.

剑指 Offer 39.

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

  1. 第一种方法用哈希表,也是最容易想到的方法,时间复杂度O(N),空间复杂度O(N)
  2. 第二种方法用投票法,时间复杂度O(N),空间复杂度O(1)

哈希

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        #哈希表,时间复杂度on,空间复杂度on
        n = len(nums)
        hash = {}
        for i in nums:
            if i in hash:
                hash[i]+=1
            else:
                hash[i] = 1
            if hash[i] > n/2:
                return(i)

投票,参考链接

#投票法,时间复杂度on空间复杂度o1
   class Solution:
    	def majorityElement(self, nums: List[int]) -> int:

        #投票法,时间复杂度on空间复杂度o1
        vote = 0
        for num in nums:
            if vote == 0:
                x = num
            if num == x:
                vote+=1
            else:
                vote-=1
        #判断是否有众数
        count = 0
        for i in nums:
            if i == x:
                count+=1
        if count < len(nums)/2:
            return(False)
        return(x)

猜你喜欢

转载自blog.csdn.net/AWhiteDongDong/article/details/114172352