Leetcode - Majority Element II

[分析] Majority Element II这个扩展版可以沿用Majority Element 中的Moore Voting解法,大于 N / 3最多有两个,遍历过程中记录两个候选值。需注意的是,遍历结束后的候选值并不一定符合条件,比如input= [1,1,2],因此需要个检查过程。
[ref]
对Moore Voting算法解析
[url]http://blog.youkuaiyun.com/joylnwang/article/details/7081575[/url]


public class Solution {
public List<Integer> majorityElement(int[] nums) {
// Moore voting
List<Integer> result = new ArrayList<Integer>();
if (nums == null || nums.length == 0) return result;
int N = nums.length;
int cand1 = nums[0], counter1 = 1;
int i = 1;
while (i < N && cand1 == nums[i]) {
counter1++;
i++;
}
if (i == N) {
result.add(cand1);
return result;
}
int cand2 = nums[i++], counter2 = 1;
while (i < N) {
if (nums[i] == cand1) {
cand1 = nums[i];
counter1++;
} else if (nums[i] == cand2) {
cand2 = nums[i];
counter2++;
} else {
if (counter1 == 0) {
cand1 = nums[i];
counter1++;
} else if (counter2 == 0) {
cand2 = nums[i];
counter2++;
} else {
counter1--;
counter2--;
}
}
i++;
}
// check cand1 & cand2
int c1 = 0, c2 = 0;
for (int j = 0; j < N; j++) {
if (cand1 == nums[j])
c1++;
else if (cand2 == nums[j])
c2++;
}
if (c1 > N / 3)
result.add(cand1);
if (c2 > N / 3)
result.add(cand2);
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值