给定一个大小为n的数组,找到其中的“多数元素”。多数元素指的是出现次数超过 ⌊ n/2 ⌋ 次的元素。
假定数组非空,且给定的数组中一定存在多数元素。
方法1:
排序,因为多数元素存在,所以排序后中位数为多数元素
class Solution(object):
def majorityElement(self,nums):
nums.sort()
return nums[len(nums)/2]
方法2:
使用后camdidate与count计数,出现一次则count加1,没有出现一次则count - 1,以此遍历
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
candidate,count = None,0
for i in nums:
if count == 0:
candidate = i
count = 1
elif candidate == i:
count += 1
else:
count -= 1
return candidate
方法3:
使用python的get()函数进行计数。
计数方法是
dict[i] = dict.get(i,0) + 1
出现一次i,字典中的key作为计数加1
get()函数:
get( i ,0) : 如果在字典里查找到了i , 则初始化为0 , 加1后为dict = {i : 1} 。当第二次遇到 i 时,dict.get(i)(此时方法括号内的0不起作用,因为其初始化作用已完成)为1,加1后为dict = {i :2}
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
for i in nums:
dict[i] = dict.get(i,0) + 1
if dict[i] > len(nums)/2:
return i