声明:
今天是第38道题。给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
解法1。常规解法就是把nums数组里的每个元素存到字典中,键值为出现频数,然后遍历这个字典,返回键值>n/2的键。提交中击败了78.78% 的用户,代码如下。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
for i in nums:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
for i in dict:
if dict[i] > len(nums)/2:
return i
return False
解法2。利用set()数据结构自动去重的特点,以及python自带的.count()函数对每个元素进行频数统计返回大于n/2的元素。在提交中击败了93.56% 的用户,代码如下。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
unique = set(nums)
for i in unique:
if nums.count(i)>len(nums)/2:
return i
return None
解法3。题干假定数组中一定存在众数(出现频数>n/2),所以可对数组进行排序返回中间的值,肯定是众数,在提交中击败了78.78% 的用户,代码如下。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(nums)[len(nums)/2]
解法4。利用max来求得最大值,可以先创建1个字典存放元素和其出现频数,再利用max可迭代的特性,求取字典中键值最大对应的元素,在提交中击败了78.78% 的用户,代码如下。
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
for i in nums:
if i not in nums:
dict[i] = 1
else:
dict[i] += 1
# dict.items()返回可遍历的(键, 值) 元组数组,比较key = dict.items()的键值,也就是第2个元素的最大值
# 最后取这个元组的第1个元素即键
return max(dict.items(), key=lambda x: x[1])[0]
结尾
解法1:原创
解法2:https://blog.csdn.net/ma412410029/article/details/80528318
解法3:https://blog.csdn.net/qq_34364995/article/details/80544139
解法4:https://blog.csdn.net/qq_34364995/article/details/80544139