python如何求一个众数

Python017

python如何求一个众数,第1张

给定一个长度为n的数组,返回众数。众数是指数组中出现次数超过n/2次的元素假设数组非空,众数一定存在Example 1:Input: [3,2,3]Output: 3Example 2:Input: [2,2,1,1,1,2,2]Output: 21:字典,累记数组中出现的各元素的次数,一旦发现超过n/2次的元素就返回该元素def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""if len(nums)==1:return nums[0]numDic = {}for i in nums:if numDic.has_key(i):numDic[i] += 1if numDic.get(i)>=(len(nums)+1)/2:return ielse:numDic[i] = 12:利用list.count()方法判断(注意for循环中如果是访问整个nums列表会出现“超出时间限制”的错误)def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""for i in nums[len(nums)//2:]:if nums.count(i)>len(nums)//2:return i3:sorted(nums)[len(nums)//2]def majorityElement(self, nums):""":type nums: List[int]:rtype: int"""return sorted(nums)[len(nums)//2]

count = {}

for n in nums:

if n in count:

count[n] += 1

else:

count[n] = 1

res = 0

maxCount = 0

for k, v in count.items():

if v >maxCount:

res = k

maxCount = k

print(res)

使用特定代码求。

众数是指在统计分布上具有明显集中趋势点的数值,代表数据的一般水平。也是一组数据中出现次数最多的数值,有时众数在一组数中有好几个,用M表示。

众数是样本观测值在频数分布表中频数最多的那一组的组中值,主要应用于大面积普查研究之中。

众数是在一组数据中,出现次数最多的数据,是一组数据中的原数据,而不是相应的次数。