解法一
class Solution {
public int majorityElement(int[] nums) {
//map
int maxCount = -1, result = -1;
Map<Integer, Integer> map = new HashMap<>();
//放到map中统计个数
for (int num : nums) {
int count = map.getOrDefault(num, 0) + 1;
map.put(num, count);
//放完之后判断当前是否为最大
if (count > maxCount) {
maxCount = count;
result = num;
}
}
return result;
}
}
解法二
摩尔投票法
class Solution {
public int majorityElement(int[] nums) {
//摩尔投票法
int votes = 0, result = -1;
for(int num : nums) {
if (votes == 0) {
result = num;
votes++;
}
else if (num == result) votes++;
else votes--;
}
return result;
}
}
摩尔投票法用于找出出现个数超过一半的目标值。