数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1 。请设计时间复杂度为 O(N) 、空间复杂度为 O(1) 的解决方案。 示例 1: 输入:[1,2,5,9,5,9,5,5,5] 输出:5 示例 2: 输入:[3,2] 输出:-1
class Solution {
public int majorityElement(int[] nums) {
/**
摩尔投票法 模板
*/
int candidate=-1,vote=0;
for(int num:nums){
if(vote==0){
//还没有初始化
candidate=num;
}
if(candidate==num){
//一样
vote++;
}else{
//不一样
vote--;
}
}
int count=0;//记录出现的candidate次数
for(int i:nums){
if(i==candidate){
count++;
}
}
if(count>nums.length/2){
return candidate;
}else{
return -1;//没找到
}
}
}