给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
方法一: 利用之前学过的字典的方法,效率还可以接受,但是这个防范具有普世性,博主也比较喜欢
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) / 2
dic = {}
for item in nums:
if item not in dic:
dic[item] = 1
else:
dic[item] += 1
for item in nums:
if dic[item] > n:
return item
方法二:技巧性比较强,是时间复杂度相当低的方法,就这道题目而言相当不错,充分结合Python方法和集合的属性:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for item in set(nums):
if nums.count(item) > (len(nums) / 2):
return item