Table of Contents
一、中文版
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
二、英文版
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三、My answer
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums) // 2
dict_ = {}
for num in nums:
if num in dict_:
dict_[num] += 1
else:
dict_[num] = 1
for key in dict_:
if dict_[key] > n:
四、解题报告
我的算法很简单,遍历数组,将数组中数字 num 及 num 出现的个数存到字典中,再遍历字典找出 value 值大于 n/2 的 key 即可。
注意 Python 中 // 除法已经是取地板,而 / 表示 float 型,精确到小数的除法。
此外有两个版本的代码值得学习:
class Solution:
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
上述方法是 LeetCode 的官方解法,学到了 Counter() ,更见识到了 max() 的方法,准备单独整理一篇博客讲 max() 的用法。
class Solution:
def majorityElement(self, nums):
majority_count = len(nums)//2
for num in nums:
count = sum(1 for elem in nums if elem == num)
if count > majority_count:
return num
上述代码在 http://www.yidianzixun.com/article/0OKPjsSp 中看到,觉得该方法中 count 的求法很是巧妙。虽然该算法时间复杂度为 O(n^2) 会超时,但仍然止不住我对它的喜爱,链接中还有很多其他的经典算法,如果感兴趣可以去学习。
不知道引用链接是否算侵权,如果原作者觉得不妥,三妹立马删掉哈。