方法一:

将数组的不同的数以字典的形式存储起来,key值是数组的数,value值是在数组中出现的次数,取value大于2/len(nums)的key

1.代码:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        elem_dict={}
        for i in nums:
            if i not in elem_dict:
                elem_dict[i]=1
            else:
                elem_dict[i] += 1
        for i in elem_dict:
            if elem_dict[i]>len(nums)/2:

                return i

2.结果:(效果不太好)

leetcode-169-求众数

方法二:

采用先排序然后取中间值的方法,因为众数的数目是大于len(num)/2

一、代码

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()

        return nums[len(nums)/2]

二、结果

leetcode-169-求众数

相关文章:

  • 2021-06-27
  • 2021-08-24
  • 2021-07-23
  • 2022-01-04
  • 2021-11-23
  • 2021-07-30
  • 2022-12-23
  • 2021-08-06
猜你喜欢
  • 2021-12-04
  • 2021-05-18
  • 2022-01-16
  • 2021-08-28
  • 2021-10-16
  • 2022-12-23
相关资源
相似解决方案