题目详情:https://leetcode.com/problems/majority-element/description/
自己写的代码,原本超时了,修改后,AC了。
# -*- coding:utf-8 -*-
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count={}
length=len(nums)
number=0
numberLength=0
for i in range(0,length):
if count.get(nums[i],-1)==-1:#不存在的话
count[nums[i]]=1#那么添加到count中
if count[nums[i]]>length/2 :
return nums[i]
else: #如果存在的话
count[nums[i]]=count[nums[i]]+1 #将出现的次数加1
if count[nums[i]]>length/2 : #探测到某个数出现的次数较多
return nums[i]
return number
看到别人写的代码,感觉好弱啊
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# if len(nums)==1:
# return nums[0]
nums.sort()
return nums[len(nums)/2]
可以这样写,是因为majority元素出现的次数超过了length/2。该元素排序后,无论在最前边还是在最后边都会在中点处有该元素。