Leetcode May Challenge - 05/06: 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.

例子

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

解释

给一堆数字,如果一个数字出现的次数占数字总数的一半以上,我们叫他majority element。现在要把这个majority找出来。保证majority element存在且数组非空。

思路

思路1 排序+sliding window

我们首先把数组排序,这样保证了所有相同的元素会连续出现。此时我们用一个长度为 数组长度一半 + 1 的窗口从0开始滑。只要窗口左边界和右边界的元素一样,则证明该元素就是我们要找的majority element。
时间复杂度 O(nlogn),空间复杂度O(1)

思路2 哈希

我们用字典把每个元素出现过的次数统计出来,然后对字典遍历,如果字典的某一个value比数组长度的一半要大,则该value对应的key即为我们要找的majority element。
时间复杂度O(n),空间复杂度O(n)

思路3 摩尔投票法

用一个counter来计数,设一个暂时结果为res,然后对数组进行遍历。如果当前数字和res相同则counter加1,不同则counter减1。如果counter等于0,则把暂时见过替换为数组当前遍历到的值。在遍历结束时,暂时结果即为最终结果。
时间复杂度O(n),空间复杂度O(1)。

代码

思路1代码

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        for i in range(n // 2 + 1):
            if nums[i] == nums[n // 2 + i]:
                return nums[i]

思路2代码

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        import collections
        c = collections.Counter(nums)
        for key in c:
            if c[key] > len(nums) // 2:
                return key

思路3代码

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 1
        res = nums[0]
        for i in range(1, len(nums)):
            if count == 0:
                res = nums[i]
                count = 1
            else:
                if nums[i] == res:
                    count += 1
                else:
                    count -= 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值