1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第一百六十九题
(1)题目
英文:
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.
中文:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
(2)解法
① 使用现成的collections.Counter
(耗时:44ms,内存:15.2M)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return [k for k, v in collections.Counter(nums).items() if v>len(nums)//2][0]
② 先用set过滤掉重复的元素,然后再用count来计数
(耗时:40ms,内存:15.1M)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
set1 = set(nums)
for i in set1:
if nums.count(i) > (len(nums)//2):
return i
③ 使用hash表,也就是生成一个key为元素,value为出现次数的dict
(耗时:56ms,内存:15.2M)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = {}
set1 = set(nums)
for i in nums:
dic[i] = dic.get(i,0) + 1
for i in set1:
if dic.get(i)>(len(nums)//2):
return i
注意:
1.get函数是获取i的value,也就是出现的次数,如果没有找到i,则是第一次出现,返回0次。