leetcode169寻找出现次数最多的数

在一个长度为n的数组中,寻找出现次数大于n/2的数

169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more thann/2times.

You may assume that the array is non-empty and the majority element always exist in the array.

最直接的思路,用一个字典保存所有数出现的次数,当出现大于n/2的直接返回

1
2
3
4
5
6
7
8
9
10
11
class (object):
def majorityElement(self, nums):
d = dict()
l = len(nums)
for i in range(l):
if(d.has_key(nums[i])):
d[nums[i]] = d[nums[i]]+1
else:
d[nums[i]] = 0
if(d[nums[i]]>=l/2):
return nums[i]

看到别人的思路,把数组排序,中间的值一定是出现次数大于等于2的值

1
2
3
4
class (object):
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)/2]