求众数Python3

提出问题:给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在众数。 解决思路:判断众数实则是判断重复元素的个数。遇到重复元素首先考虑字典。字典key值存放数组元素,value存放元素出现次数,如果次数超过n/2,则为答案。 代码如下( ̄▽ ̄): class Solution: def majorityElement(self, nums: List[int]) -> int: d = {} for i in nums: if i in d: d[i]+=1 else: d[i]=1 for key,value in d.items(): if d[key] > len(nums)/2: return key return 0时间与空间复杂度: 题目来源:https://leetcode-cn.com/probl...

October 1, 2019 · 1 min · jiezi