leetcode笔记--Majority Element I & II



Majority Element

题目:难度(Easy)
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.
Tags:Array, Divide and Conquer, Bit Manipulation

法1:利用python 容器Counter的most_common方法,返回出现次数最多的n个元素,每个元素以(值,计数)元组,组成list返回

代码实现:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        from collections import Counter
        return Counter(nums).most_common(1)[0][0]

法2:多数投票算法,求出众数,但众数不一定就次数大于n/2,还需要再遍历一遍数组,对求得的众数出现次数进行验证。但题目已经告知一定存在大于n.2次数的数,所以这里不需验证。另外注意,次数大于n/2的数只可能有一个

代码实现:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """        
    #多数投票算法
    #题目已经告知数组非空,且majority element一定存在
    def majorityElement(self, nums):
        n = len(nums)
        count = 1#候选者的票数
        candidate = nums[0]#候选者
        for i in range(1, n):
            if count == 0:#更新新的候选者
                candidate = nums[i]
                count += 1
            elif candidate == nums[i]:
                count += 1
            else:
                count -= 1
        return candidate


Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Hint:
How many majority elements could it possibly have?
Tags:Array

法1:同样也可以使用Counter.most_common方法,缺点:使用了hash表,空间复杂度为O(n),但题目要求空间复杂度是O(1)

代码实现:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        result = []
        from collections import Counter
        for item in Counter(nums).most_common(2):
            if item[1]>n/3:
                result.append(item[0])
        return result
        #缺点:使用了hash表,空间复杂度为O(n),但题目要求空间复杂度是O(1)

法2:多数投票算法,求出众数,然后验证众数的出现次数是否大于n/3,大于n/3的数只可能有2个,1个或没有。

代码实现:

class Solution(object):
    #多数投票算法,时间复杂度是O(n),空间复杂度是O(1)  
    #此时的众数至多只可能有2个
    def majorityElement(self, nums):
        n = len(nums)
        count1, count2 = 0, 0
        c1, c2 = None, None
        for i in range(n):
            if c1 == nums[i]:#1
                count1 += 1
            elif c2 == nums[i]:#2
                count2 += 1
            elif count1 == 0:#3
                c1 = nums[i]
                count1 += 1
            elif count2 == 0:#4
                c2 = nums[i]
                count2 += 1
            else:#5
                count1 -= 1
                count2 -= 1
                
        #验证:
        count1, count2 = 0, 0
        for num in nums:
            if num == c1:
                count1 +=1
            if num == c2:
                count2 +=1
        result = []
        if count1 > n/3:
            result.append(c1)
        if count2 > n/3:
            result.append(c2)
        return result

注意:上述求众数模块中的5个条件语句的顺序不能打乱,1,2句一定要在3,4句之前,这样能保证c1,c2指向的不是同一个数,3,4句一定要在5句的前面,这样能保证count1,count2不会变成负数。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值