169. Majority Element@python

Given an array of size n, find the majority element. The majority element is the element that appears more than⌊ n/2 ⌋ times.數組

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

原題地址: Majority Elementspa

難度: Easycode

題意: 找出數量超過數組長度一半的值blog

思路1:排序

對數組進行排序, 因爲某個值的數量超過數組長度的一半,排序以後,數組中間的值必然是要求的結果ip

代碼:element

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[len(nums)/2]    

時間複雜度: O(nlog(n)),即排序的複雜度leetcode

空間複雜度: O(1)get

 

思路2:

遍歷數組,進行統計

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = {}
        for num in nums:
            d[num] = d.get(num, 0) + 1
            if d[num] > len(nums) / 2:
                return num    

時間複雜度: O(n)

空間複雜度: O(n)

 

思路3:

摩爾投票法: 將數組中不一樣兩個數配成對

代碼:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        count = 1
        num = nums[0]
        for i in range(1, n):
            if nums[i] == num:
                count += 1
            elif count == 0:
                num = nums[i]
                count += 1
            else:
                count -= 1
        
        count = 0
        for i in range(n):
            if nums[i] == num:
                count += 1
        
        if count > n / 2:
            return num

時間複雜度: O(n)

空間複雜度: O(1)

相關文章
相關標籤/搜索