算法练习5——多数元素

LeetCode 多数元素

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

蛮力法

  1. 双重循环,不过会超时
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        times = 0
        for i in nums:
            for j in nums:
                if i == j:
                    times += 1
            if times > len(nums) / 2:
                return i
            times = 0
  1. 随机抽取,随机抽取一个元素为过半众数的概率大于1/2,该方法是基于数据特点对双重循环进行优化
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        majority_count = len(nums) // 2
        while True:
            candidate = random.choice(nums)
            if sum(1 for elem in nums if elem == candidate) > majority_count:
                return candidate

# 作者:力扣官方题解
# 链接:https://leetcode.cn/problems/majority-element/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  1. 哈希表计数
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counts = collections.Counter(nums)
        return max(counts.keys(), key=counts.get)

# 作者:力扣官方题解
# 链接:https://leetcode.cn/problems/majority-element/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

数学方法,基于数据特征

  1. Boyer-Moore 投票算法
    过半众数是数组中出现次数最多的数据,如果每次从数组中抽取两个不同的数据,最后数组中剩下的一定是众数。
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        item, times = nums[0], 1
        for idx in range(1, len(nums)):
            if nums[idx] != item:
                if times > 0:
                    times -= 1
                else:
                    item = nums[idx]
                    times = 1
            else:
                times += 1
        return item

还是官方写的简洁啊

python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count = 0
        candidate = None

        for num in nums:
            if count == 0:
                candidate = num
            count += (1 if num == candidate else -1)

        return candidate

# 作者:力扣官方题解
# 链接:https://leetcode.cn/problems/majority-element/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  1. 排序取中间值
    过半众数排序后,n/2位置处数据一定是过半众数
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums) // 2]

# 作者:力扣官方题解
# 链接:https://leetcode.cn/problems/majority-element/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
谎言西西里1 天前
LeetCode 热题100 --- 双指针专区
算法
leo__5201 天前
基于两步成像算法的聚束模式SAR MATLAB实现
开发语言·算法·matlab
前端小白在前进1 天前
力扣刷题:在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
某林2121 天前
基于SLAM Toolbox的移动机器人激光建图算法原理与工程实现
stm32·嵌入式硬件·算法·slam
修炼地1 天前
代码随想录算法训练营第四十三天 | 图论理论基础、深搜理论基础、卡码网98. 所有可达路径、797. 所有可能的路径、广搜理论基础
算法·深度优先·图论
iAkuya1 天前
(leetcode)力扣100 23反转链表(迭代||递归)
算法·leetcode·链表
剪一朵云爱着1 天前
PAT 1095 Cars on Campus
算法·pat考试
MicroTech20251 天前
激光点云快速配准算法创新突破,MLGO微算法科技发布革命性点云配准算法技术
人工智能·科技·算法
Cathy Bryant1 天前
傅里叶变换(一):简介
笔记·算法·数学建模·信息与通信·傅里叶分析
allan bull1 天前
在节日中寻找平衡:圣诞的欢乐与传统节日的温情
人工智能·学习·算法·职场和发展·生活·求职招聘·节日