- 多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
投票算法:
先假设一个数,然后不断判断,如果下一个数是该数,那么就直接多加一票,如果下一个不是这个数,那么就减一票,由于该数的个数大于 ⌊ n/2 ⌋,所以最后加减后,一定可以找到该数。
public static int majorityElement(int[] nums) {
int restemp=nums[0];
int times=1;
for(int i=1;i<nums.length;i++){
if(times==0){
restemp=nums[i];
times=1;
}else {
if(nums[i]==restemp)times++;
else times--;
}
}
return restemp;
}