LeetCode Majority Element
来源:互联网 发布:积分兑换源码 编辑:程序博客网 时间:2024/06/05 17:02
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.
思路分析:求主元素的经典算法是Moore投票算法,基本可以理解为将主元素和不同元素一一对应相消,最后剩下来的元素就是主元素。具体做法是,初始计数器times和candidate都是0,然后遍历数组,当times为0时置换新的candidate,遇到和candidate相同元素times++,遇到和candidate相异元素times--,如此操作,如果主元素存在,最后剩下的一定是主元素。时间复杂度O(n),空间复杂度O(1).
AC Code
public class Solution { public int majorityElement(int[] nums) { //0627 //Moore Voting int n = nums.length; int candidate = 0; int times = 0; for(int i = 0; i < n; i++){ if(times == 0) candidate = nums[i]; if(nums[i] != candidate){ times--; } else{ times++; } } return candidate; //0631 }}
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- Google MapReduce/GFS/BigTable三大技术的中文版
- linux的主分区与逻辑分区的关系
- 自建的C语言可执行程序运行后结果显示窗口不关闭
- javascript获取url各种信息
- 管理Pivotal Gemfire的系统输出文件
- LeetCode Majority Element
- Storm Trident Example 代码阅读笔记
- 关于oracle endian_format的相关解释
- 版本发布后软件测试人员要做的工作
- thinkphp模块部分学习
- Linux中TCP连接过程状态简介
- AVFoundation视频播放(非音视频流处理)
- Hiho1186/ 第五十五周 连通性·四 点双连通分量
- 单元格跨行合并,单元格跨列合并