求众数(python实现)

风格不统一 提交于 2019-11-28 22:46:47

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

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

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element

思路:遍历nums,再另设一个数组记录元素出现次数

代码:

class Solution:
    def majorityElement(self, nums) -> int:
        lst=[]
        n=len(nums)
        count=[0]*n
        
        for i in nums:
            if i not in lst:
                lst.append(i)
                index=lst.index(i)
                count[index]+=1
                if count[index]>n/2:
                    return i
            else:
                index=lst.index(i)
                count[index]+=1
                if count[index]>n/2:
                    return i
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!