Sort, and the molar voting method is a good method.
Part of the code reference sources: https: //leetcode-cn.com/problems/majority-element/solution/3chong-fang-fa-by-gfu-2/
public int majorityElement1(int[] nums) {
int len = nums.length;
int midLen = len >> 2;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; i++) {
if (map.containsKey(nums[i])){
map.put(nums[i],map.get(nums[i]) + 1);
} else {
map.put(nums[i],1);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
if (entry.getValue() > midLen){
return entry.getKey();
}
}
return 0;
}
//排序法
public int majorityElement2(int[] nums){
Arrays.sort(nums);
return nums[nums.length >> 1];
}
//摩尔投票法
public int majorityElement3(int[] nums){
int cand_num = nums[0],count = 1;
for (int i = 1; i < nums.length; ++i) {
if (nums[i] == cand_num){
++count;
} else {
if (--count == 0){
cand_num = nums[i];
count = 1;
}
}
}
return cand_num;
}