哈希表统计法: 遍历数组 nums ,用 HashMap 统计各数字的数量,即可找出 众数 。此方法时间和空间复杂度均为 O(N)O(N) 。
数组排序法: 将数组 nums 排序,数组中点的元素 一定为众数。
摩尔投票法: 核心理念为 票数正负抵消 。此方法时间和空间复杂度分别为 O(N)O(N) 和 O(1)O(1) ,为本题的最佳解法。
1.
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int x = array[0];
int votes = 0;
for(int i=0;i<array.length;i++){
if(votes == 0) x = array[i];
if(x == array[i]) votes++;
else votes--;
}
return x;
}
}2.
hashmap.
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i =0; i< array.length; i++){
if(!map.containsKey(array[i])){
map.put(array[i],1);
}
else {
map.put(array[i],map.get(array[i])+1);
if(map.get(array[i]) >= (array.length+1)/2 ) return array[i];
}
}
return array[0];
}
}


京公网安备 11010502036488号