【leetcode--169.多数元素】

返回数组中超过长度半数数量的元素的值

一开始想的是进行sort排序,然后取中间值与两头的分别比对一下,如果一致就返回。

复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort(reverse = True)
        n = len(nums)
        mid = int(n // 2)
        if nums[n-1] == nums[mid] or nums[0] == nums[mid]:
            return nums[mid]
        else:
            return 0

但是提交的时候发现还有这种情况:

于是调整一下思路:

因为排序后的数组,如果存在一个数超过数组长度一半,中位数一定是那个数,所以使用Counter计数,只需要判断中位数的次数有没有超过长度一半即可

复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort(reverse = True)
        n = len(nums)
        mid = int(n // 2)
        counts = Counter(nums)
        if counts[nums[mid]]>= mid :
            return nums[mid]
        else:
            return 0
相关推荐
likexuec5 小时前
数据结构(2)
数据结构
文丑颜不良啊6 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z6 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH7 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶8 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊8 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊8 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
文丑颜不良啊10 小时前
LeetCode2141~2160题目解析
java·leetcode
LabVIEW开发10 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview