Leetcode刷题笔记python----求众数

求众数

题目

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

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

示例 1:

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

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


解答

思路:

  1. set求单一元素
  2. 遍历。count()求和
    3.判断得到结果

代码:

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n=set(nums)
        for i in n:
            if nums.count(i)>len(nums)/2:
                return i

结果:60%

猜你喜欢

转载自blog.csdn.net/sinat_29350597/article/details/82918128
今日推荐