给定一个数组(长度为n),找出“多数元素”(出现次数大于n/2),假定数组不为空且“多数元素”一定存在。
思路一:
将数组排序,则最中间的那个数一定是“多数元素”。
时间复杂度:O(n*lgn)
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return nums[len(nums)//2]
思路二:
使用dict用来记录数组里每个数出现的次数。
空间复杂度:O(n),时间复杂度:O(n)
class Solution(object):
def majorityElement(self, nums):
count = {}
for i in nums:
if i in count:
count[i] += 1
else:
count[i] = 1
return max(count, key=count.get)
- 相关知识点:
get():返回指定键的值,如果值不在字典中则返回默认值。