leetcode-169. 求众数

题目

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

思路

  1. 大于 ⌊ n/2 ⌋ 的元素有且只有一个,所以找到出现次数最多次的元素即可
  2. 将元素和元素出现的次数存在dict里面
  3. 将dict按照value值进行排序,并得到逆序

代码如下:

import operator
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        lens = len(nums)
        numsDict = {}
        for i in range(lens):
            numsDict[nums[i]] = numsDict.get(nums[i],0)+1
        listNums = sorted(numsDict.items(),key = operator.itemgetter(1),reverse=True)
        return listNums[0][0]

学习他人代码

  1. 去重,得到tmp
  2. 循环tmp里面的元素,得到这个元素在nums里面的个数
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)/2
        tmp = list(set(nums))
        for i in tmp:
            if nums.count(i) > n:
                return i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值