LeetCode 169. 多数元素 Majority Element

简介: LeetCode 169. 多数元素 Majority Element

LeetCode 169. 多数元素 Majority Element


Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告

一、中文版

给定一个大小为 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) 会超时,但仍然止不住我对它的喜爱,链接中还有很多其他的经典算法,如果感兴趣可以去学习。

不知道引用链接是否算侵权,如果原作者觉得不妥,三妹立马删掉哈。

相关文章
|
16天前
|
算法
【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题:翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题:翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
|
1天前
|
存储 算法 Java
力扣经典150题第四十五题:存在重复元素 II
力扣经典150题第四十五题:存在重复元素 II
5 0
|
24天前
|
算法 搜索推荐 Java
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
【经典算法】LeetCode 215. 数组中的第K个最大元素(Java/C/Python3实现含注释说明,Medium)
15 3
|
10天前
|
索引
leetcode题解:27.移除元素
leetcode题解:27.移除元素
11 0
|
1月前
题目----力扣--移除链表元素
题目----力扣--移除链表元素
24 1
|
1月前
|
存储 算法 索引
【力扣刷题】只出现一次的数字、多数元素、环形链表 II、两数相加
【力扣刷题】只出现一次的数字、多数元素、环形链表 II、两数相加
31 1
|
1月前
|
人工智能
力扣100114. 元素和最小的山形三元组 II(中等)
力扣100114. 元素和最小的山形三元组 II(中等)
|
20天前
|
存储 SQL 算法
LeetCode 83题:删除排序链表中的重复元素【面试】
LeetCode 83题:删除排序链表中的重复元素【面试】
|
20天前
|
存储 SQL 算法
LeetCode 题目 82:删除排序链表中的重复元素 II
LeetCode 题目 82:删除排序链表中的重复元素 II
|
20天前
|
SQL 算法 数据可视化
Leetcode27题:移除元素【27/1000 python】
Leetcode27题:移除元素【27/1000 python】