169. Majority Element@python

Posted Chim

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

原题地址: Majority Element

难度: Easy

题意: 找出数量超过数组长度一半的值

思路1:

对数组进行排序, 由于某个值的数量超过数组长度的一半,排序之后,数组中间的值必然是要求的结果

代码:

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

时间复杂度: O(nlog(n)),即排序的复杂度

空间复杂度: O(1)

 

思路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)

 

以上是关于169. Majority Element@python的主要内容,如果未能解决你的问题,请参考以下文章

169. Majority Element@python

169. Majority Element

Leetcode 169. Majority Element

169. Majority Element

169. Majority Element

LeetCode169. Majority Element