Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
将每个元素出现的次数用 Map 保存起来,返回出现次数最多的元素。
时间复杂度:O(n);空间复杂度:O(n)
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
maxE = maxV = 0
for val in nums: # 统计每个元素的个数
if count.get(val):
count[val] += 1
else:
count[val] = 1
for key, val in count.items():
if val > maxV:
maxE, maxV = key, val
return maxE
a = [3,2,3,3]
b = Solution()
print(b.majorityElement(a)) # 3
return sorted(nums)[len(nums)/2]
public class Solution {
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
}
方法2完美地抓住了列表中元素超过 n/2 次的条件,只不过我想不到。