leetcode 169. Majority Element python

给定一个大小为n的数组,找到其中的“多数元素”。多数元素指的是出现次数超过 ⌊ n/2 ⌋ 次的元素。 

假定数组非空,且给定的数组中一定存在多数元素。

方法1:

排序,因为多数元素存在,所以排序后中位数为多数元素

class Solution(object):
    def majorityElement(self,nums):
        nums.sort()
        return nums[len(nums)/2]

方法2:

使用后camdidate与count计数,出现一次则count加1,没有出现一次则count - 1,以此遍历

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        candidate,count = None,0
        for i in nums:
            if count == 0:
                candidate = i
                count = 1
            elif candidate == i:
                count += 1
            else:
                count -= 1
        return candidate

方法3:

使用python的get()函数进行计数。

计数方法是

 dict[i] = dict.get(i,0) + 1
出现一次i,字典中的key作为计数加1

get()函数:

get( i ,0) : 如果在字典里查找到了i , 则初始化为0 , 加1后为dict = {i : 1} 。当第二次遇到 i 时,dict.get(i)(此时方法括号内的0不起作用,因为其初始化作用已完成)为1,加1后为dict = {i :2}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值