Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times.
Note: The algorithm should run in linear time and in O(1) space.
class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> list=new ArrayList<>(); if(nums==null||nums.length==0) return list; int a=0, b=0, ca=0, cb=0; for(int n:nums){ if(n==a) ca++; else if(n==b) cb++; else if(ca==0){ a=n;ca=1; } else if(cb==0){ b=n;cb=1; } else{ ca--;cb--;} } ca=0;cb=0; for(int n:nums){ if(n==a) ca++; else if(n==b) cb++; } if(ca>nums.length/3) list.add(a); if(cb>nums.length/3) list.add(b); return list; } }
moore voting algorithm
注意:
169中第一个for循环中,判断ca是否为0和判断a是否等于n的前后顺序无所谓,但在这里,要注意a、b的顺序,对cb是否为0的判断要放在对a和ca的判断的后面,否则,对于例如:[7,7,8,8,8]就会出错,开始会分别把a和b都变成7。
一个数组中appear more than ⌊ n/3 ⌋
times的数不会超过2个,证明见 https://blog.csdn.net/tinyjian/article/details/79110473
这里题目没有给出一定会有解或是有几个解之类,最后必须要重新过一遍数组确定a,b是否满足题意。