leetcode 【 Majority Element 】python 实现
题目:
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.
代码:oj测试通过 Runtime: 197 ms
1 class Solution: 2 # @param num, a list of integers 3 # @return an integer 4 def majorityElement(self, num): 5 if len(num) == 1: 6 return num[0] 7 8 candidate = 0 9 count = 0 10 for i in range(len(num)): 11 if count == 0: 12 candidate = num[i] 13 count += 1 14 else: 15 if num[i] == candidate : 16 count += 1 17 else: 18 count -= 1 19 return candidate
思路:
这个自己想不出来。上网找的Moore Voting算法。
这个方法在思路上还是比较朴实无华的,但是很精妙。
注意题目的条件,重复出现大于数据长度一半的元素为众数。
因此可以采用一种对冲思路:一旦相邻的两个元素不同,就把这两个元素对冲抵消掉;由于众数的出现频次大于数据其他所有元素出现频次之和,所以这种对冲抵消最后剩下的一定是众数。
之前看过几篇日志说这道题 还不错 记录在下面:
http://www.yanyulin.info/pages/2014/12/851338983752.html
http://www.geeksforgeeks.org/majority-element/
http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?