问题描述:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
原来是读题读错了。。。
方法1:
1 class Solution(object): 2 def majorityElement(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 nums.sort() 8 wid = len(nums) // 2 9 i = 0 10 n_count = 0 11 dicts = {} 12 while i < len(nums): 13 temp = nums[i] 14 n_count = nums.count(temp) 15 dicts[temp] = n_count 16 i += n_count 17 maxnum = -1 18 for key in dicts: 19 if dicts[key] >= maxnum: 20 maxkey = key 21 maxnum = dicts[maxkey] 22 return maxkey
改进一:
1 class Solution(object): 2 def majorityElement(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 res={} 8 for one in nums: 9 if one in res: 10 res[one]+=1 11 else: 12 res[one]=1 13 14 return max(res,key=res.get) #字典中值最大的键
改进二:
1 class Solution(object): 2 def majorityElement(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 nums.sort() 8 wid = len(nums) // 2 9 i = 0 10 n_count = 0 11 while i < len(nums): 12 n_count = nums.count(nums[i]) 13 if n_count > wid : 14 return nums[i] 15 i += n_count
官方:
1 class Solution(object): 2 def majorityElement(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 nums.sort() 8 return nums[len(nums)/2]
官方二:
1 class Solution(object): 2 def majorityElement(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 res=set(nums) 8 n=len(nums)/2 9 for item in res: 10 if(nums.count(item)>n): 11 return item
2018-09-14 21:50:56