消减法。设置两个变量空间:candidate表示候选数,HP表示候选数出现的次数,基这两个变量来统计。遍历数组,把两个不同的数消去,相同的数记录出现的次数,进行叠加。
public class Solution {
public int MoreThanHalfNum_Solution(int [] nums) {
if (nums.length == 0 || nums == null){
return -1;
}
int candidate = 0; //候选数
int HP = 0; // 根据HP 更新候选数
for (int i = 0; i < nums.length; i++){
if (HP == 0){//若HP为0,将当前数设为候选数。同时将HP置为1
candidate = nums[i];
HP = 1;
}else if (nums[i] != candidate){//有候选的情况
//当前数不等于候选数,一并删除
HP--;
}else{
//有候选,且相同
HP++;
}
}
if (HP == 0){//说明没有,返回-1
return -1;
}
//遍历完成后,若有数剩下来了,那么HP一定>0。但,不知道这个数是不是水王数,
// 所以需要遍历,去统计这个数在数组中实际 出现的次数。
int count = 0;
for (int num : nums) {
if (num == candidate){
count++;
}
}
return count > (nums.length >> 1) ? candidate : -1;
}
}
京公网安备 11010502036488号