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
摩尔投票法,如果不了解这个方法想自己想我觉得真是挺难的,关于摩尔投票法http://mabusyao.iteye.com/blog/2223195讲解的比较清楚,题目提示中问符合出现次数大于n/3的众数最多有几个,答案明显是2,那么我们用两个变量a,b作为候选众数,利用摩尔投票法找出可能的众数,再次遍历数组计算出现次数是否符合条件,代码:
public List<Integer> majorityElement(int[] nums) { List<Integer> list=new ArrayList<>(); int a=0,b=0; int ca=0,cb=0; for(int num:nums){ if(num==a){ ca++; } else if(num==b){ cb++; } else if(ca==0){ a=num; ca=1; } else if(cb==0){ b=num; cb=1; } else{ ca--; cb--; } } ca=0; cb=0; for(int num:nums){ if(a==num) ca++; else if(b==num) cb++; } int len=nums.length; if(ca>len/3) list.add(a); if(cb>len/3) list.add(b); return list; }