Majority Element II:求个数多余1/3的元素
来源:互联网 发布:poi设置数据有效性 编辑:程序博客网 时间:2024/06/05 06:43
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
思路:朴素想法肯定是排序后遍历,但是限制了复杂度,所以类似于上提,考虑摩尔投票发。
首先,因为个数要大于三分之一,所以最多只能有两个止痒的元素,可以用反证法证明。
所以遍历两次,第一遍找出最大的两个元素,第二遍检验这两个元素是否满足条件。
class Solution {
public List<Integer> majorityElement(int[] nums) {
if(nums.length == 0) return new ArrayList<Integer>();
ArrayList<Integer> l = new ArrayList<Integer>();
int majority1 = Integer.MAX_VALUE;
int majority2 = Integer.MIN_VALUE;
int count1 = 0;
int count2 = 0;
for(int i = 0;i<nums.length;i++){
if(nums[i]==majority1){
count1++;
}else if(nums[i]==majority2){
count2++;
}else if(count1==0){
majority1 = nums[i];
count1 = 1;
}else if(count2==0){
majority2 = nums[i];
count2 = 1;
}else{
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for(int e:nums){
if(majority1==e) count1++;
if(majority2==e) count2++;
}
if(count1>nums.length/3) l.add(majority1);
if(count2>nums.length/3) l.add(majority2);
return l;
}
}
- Majority Element II:求个数多余1/3的元素
- 229. Majority Element II 找出出现超过一定数量的元素
- Majority Element 主要的元素
- Majority Element && Majority Element II
- LeetCode OJ 之 Majority Element II(大部分元素2)
- LeetCode-169.229. Majority Element II (JAVA)主要元素
- Majority Element众数元素的解法分析
- [LeetCode] Majority Element 最主要的元素
- Majority Element II
- [LeetCode] Majority Element II
- 229.Majority Element II
- Majority Element II
- [leetcode] Majority Element II
- Majority Element II
- #leetcode#Majority Element II
- 【LeetCode】Majority Element II
- LeetCode Majority Element II
- LeetCode - Majority Element II
- javascript中的this用法
- Fortran 错误集合
- sklearn.tree之Decision Trees
- dom4j 生成 xml ,解析xml
- [Lintcode] #41 最大子数组
- Majority Element II:求个数多余1/3的元素
- web开发快速提高工作效率的一些资源
- CNN卷积神经网络原理记录
- Oracle 字符函数
- 关于 can not find hdf5.h(hdf5:没有那个文件或目录)的解决方法
- 深度学习性能提升的诀窍
- Cortex-M0的BOD中断及重启-掉电检测的可利用性+BOD汇编启动
- Java工厂设计模式-lambda表达式简单实例
- mysql too many connections问题,kill掉所有锁表进程