⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
return res;
}
int c1 = 0;
int c2 = 0;
int m1 = 0;
int m2 = 1;
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (n == m1) {
c1++;
} else if (n == m2) {
c2++;
} else if (c1 == 0) {
m1 = n;
c1 = 1;
} else if (c2 == 0) {
m2 = n;
c2 = 1;
} else {
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for (int n : nums) {
if (n == m1) c1++;
if (n == m2) c2++;
}
if (c1 > nums.length / 3) {
res.add(m1);
}
if (c2 > nums.length / 3) {
res.add(m2);
}
return res;
}
}
没有评论:
发表评论