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/3的元素。
解题思路: 忘了在哪看见过这个的数学证明,数组中超过n/3的元素个数最多两个,本题用摩尔投票法,需要两轮计数。
第一轮:找出出现次数最多的两个元素,每次存储两个元素n1和n2,如果第三个元素与其中一个相同,则增加计数cn1或cn2, 否则,清除n1和n2,从下一个数据开始重新统计.
经过第一轮查找数目较多的元素一定可以被查到,当然查到的不一定是大于n/3的。所以第二轮就验证这两个元素是否满足条件,即出现的次数是否大于n/3;
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if (nums == null || nums.length == 0) return res;
if (nums.length == 1) {
res.add(nums[0]);
return res;
}
int n1 = 0, n2 = 0, cn1 = 0, cn2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == n1) {
cn1++;
}else if (nums[i] == n2) {
cn2++;
}else if (cn1 == 0) {
n1 = nums[i];
cn1++;
}else if (cn2 == 0) {
n2 = nums[i];
cn2++;
}else {
cn1--;
cn2--;
}
}
cn1 = 0; cn2 = 0;
for (int i = 0; i < nums.length; i++) {
if (n1 == nums[i]) {
++cn1;
}else if (n2 == nums[i]) {
++cn2;
}
}
if (cn1 > nums.length/3) res.add(n1);
if (cn2 > nums.length/3) res.add(n2);
return res;
}
}