public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if (nums.length == 0) return res;
int candidate1 = 0, count1 = 0;
int candidate2 = 0, count2 = 0;
for (int num : nums) {
if (candidate1 == num) count1++;
else if (candidate2 == num) count2++;
else if (count1 == 0) { candidate1 = num; count1 = 1; }
else if (count2 == 0) { candidate2 = num; count2 = 1; }
else { count1--; count2--; }
}
// check if cadidates are majority element
count1 = 0; count2 = 0;
for (int num : nums) {
if (num == candidate1) count1++;
// use 'else if' other than 'if' to avoid duplicate e.g. input [0, 0, 0]
else if (num == candidate2) count2++;
}
if (count1 > nums.length/3) res.add(candidate1);
if (count2 > nums.length/3) res.add(candidate2);
return res;
}
}
Leetcode 229. Majority Element II
最新推荐文章于 2020-03-26 22:59:08 发布