Majority Element

本文介绍了解决LeetCode上多数元素问题的两种方法。一种是通过记录每个元素出现次数并找到超过一半长度的元素;另一种是利用排序特性直接返回中间位置的元素,因为多数元素必定在此位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目详情:https://leetcode.com/problems/majority-element/description/
自己写的代码,原本超时了,修改后,AC了。

# -*- coding:utf-8 -*-
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count={}
        length=len(nums)
        number=0
        numberLength=0
        for i in range(0,length):
            if count.get(nums[i],-1)==-1:#不存在的话
                count[nums[i]]=1#那么添加到count中
                if count[nums[i]]>length/2 :
                    return nums[i]
            else: #如果存在的话
                count[nums[i]]=count[nums[i]]+1 #将出现的次数加1
                if count[nums[i]]>length/2 : #探测到某个数出现的次数较多
                    return nums[i]
        return number

看到别人写的代码,感觉好弱啊

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

可以这样写,是因为majority元素出现的次数超过了length/2。该元素排序后,无论在最前边还是在最后边都会在中点处有该元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值