Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 18, 2019 05:10
Show Gist options
  • Save shixiaoyu/d0e7864646e7c8295a1cac93263f0c55 to your computer and use it in GitHub Desktop.
Save shixiaoyu/d0e7864646e7c8295a1cac93263f0c55 to your computer and use it in GitHub Desktop.
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
int candidate1 = 1;
int candidate2 = 1;
int vote1 = 0;
int vote2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == candidate1) {
vote1++;
} else if (nums[i] == candidate2) {
vote2++;
} else if (vote1 == 0) { // the order of this if/else actually matters, you cannot put the 0 check first since [8, 8, 7, 7, 7]
candidate1 = nums[i];
vote1++;
} else if (vote2 == 0) {
candidate2 = nums[i];
vote2++;
} else {
vote1--;
vote2--;
}
}
/* This is what you should do if we want to put vote1 == 0 check at the beginning
for (int i = 0; i < nums.length; i++) {
if (vote1 == 0 && candidate2 != nums[i]) {
candidate1 = nums[i];
} else if (vote2 == 0 && candidate1 != nums[i]) {
candidate2 = nums[i];
}
if (nums[i] == candidate1) {
vote1++;
} else if (nums[i] == candidate2) {
vote2++;
} else {
vote1--;
vote2--;
}
}
*/
int count1 = 0;
int count2 = 0;
// need another pass to filter between the 2 candidates, e.g., [3, 2, 3], 2 is candidate but not more than 1/3
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
if (count1 > nums.length / 3) {
res.add(candidate1);
}
if (count2 > nums.length / 3) {
res.add(candidate2);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment