HashMap方法
class Solution {
public int majorityElement(int[] nums) {
int len = nums.length;
Map<Integer,Integer> map = new HashMap<>();
for(int i=0; i<len; i++){
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
if(map.get(nums[i]) > len/2) return nums[i];
}
return -1;
}
}
摩尔投票法
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for(int num:nums){
if(votes == 0) x = num;
if(num == x) votes += 1;
else votes += -1;
}
return x;
}
}