[Java] Majority Element II 找众数2
来源:互联网 发布:萧亚轩事业 知乎 编辑:程序博客网 时间:2024/06/05 16:39
leetcode 链接 :https://leetcode.com/problems/majority-element-ii/
题目
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.
简要翻译:
就是给定一个含有n个数的数组,找到所有出现次数大于⌊ n/3 ⌋次的数。算法要求线性时间复杂度O(N),空间复杂度O(1).
此题如果采用先排序在去查找的话,显然是不能满足时间复杂度的,因为基于比较的排序最快也要O(N*logN)
根据我的上一篇博客(http://blog.csdn.net/lyy_hit/article/details/47616641)的解题思路,我们是可以在O(N)的时间复杂度解决问题的。
首先我们要分析,到底有几个数是满足条件的。很显然可能的情况就是0或1或2个数,为什么大于3就不行呢? 根据反正法是可以证明的,此处省略
在实现的过程中呢,我们可以假设存在两个数是满足条件的,用两个临时变量来存储,找到这两个数之后,因为可以证明若存在,必定就是临时变量存储的这两个数。因此我们可以再次遍历一次数组来统计出现的次数,若满足条件则是所要找的数,若不满足则不是。
代码实现如下:
package com.easy;import java.util.ArrayList;import java.util.List;public class MajorityElementII{public static void main(String[] args){// TODO Auto-generated method stubint []nums = {2, 2};//{-1, 1, 1, 1, 2, 1};//{1, 3, 1, 2, 3, 4, 2, 2, 3, 3, 2};List<Integer> list = majorityElement(nums);for (int i = 0; i < list.size(); i++){System.out.println(list.get(i));}}public static List<Integer> majorityElement(int[] nums) { List<Integer> list = new ArrayList<Integer>(); int A = 0, B = 0; int cntA = 0, cntB = 0; for (int i = 0; i < nums.length; i++) { if (cntA == 0 && cntB == 0) { A = nums[i]; cntA++; }else if (cntA > 0 && cntB == 0) { if (A != nums[i]) { B = nums[i]; cntB++; }else { cntA++; } }else if (cntA == 0 && cntB > 0) { if (B != nums[i]) { A = nums[i]; cntA++; }else { cntB++; } }else { if (A == nums[i]) { cntA++; }else if (B == nums[i]) { cntB++; }else { cntA--; cntB--; } } // System.out.println("A = "+A+" cntA = " + cntA + " B = " + B + " cntB = " + cntB); } if (cntA > 0) { cntA = 0; for (int i = 0; i < nums.length; i++) { if (A == nums[i]) { cntA++; } } if (cntA > nums.length/3) { list.add(A); } } if (cntB > 0) { cntB = 0; for (int i = 0; i < nums.length; i++) { if (B == nums[i]) { cntB++; } } if (cntB > nums.length/3) { list.add(B); } } return list; }}
ps:在实现过程中要注意分情况,不能漏掉任何一种情况
0 0
- [Java] Majority Element II 找众数2
- LeetCode 229. Majority Element II(众数II)
- [Leetcode,python] Majority Element 众数
- Majority Element 和 Majority Element II LeetCode Java
- Majority Element && Majority Element II
- leetcode-java-229. Majority Element II
- LeetCode 169. Majority Element(众数)
- (LeetCode)Majority Element ---- 选众数
- Majority Element众数元素的解法分析
- 169/229 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
- hdu3695(AC自动机)
- Mongdb安全和认证
- 属性传递
- HDU 5387 Clock(分数类+模拟)
- iOS开发UI中懒加载的使用方法
- [Java] Majority Element II 找众数2
- 简单的String类
- hdu5326 Work
- 斯坦福ML公开课笔记13B-因子分析模型及其EM求解
- Jedis之ShardedJedis一致性哈希分析
- 入职 培训
- 类型别名、auto类型说明符和decltype类型说明符初探
- MYSQL replace
- pscp+psftp+putty的使用