思路:
1.哈希表
2.排序,排序完后出现次数最多的数一定在中间位置
3.摩尔投票, 将出现次数超过一半的数字记为众数,若记众数的票数为 +1 ,非众数的票数为 -1 ,则一定有所有数字的票数和 >0 。
public static int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
if (map.get(num) > nums.length / 2){
return num;
}
}
return 0;
}
public static int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
这个解法限定一定存在众数的情况
public int majorityElement(int[] nums) {
// 众数 x 票数 votes
int x = 0, votes = 0;
for (int num : nums) {
// 如果票数为0,则假设当前数字num是众数
if (votes == 0) x = num;
// 当 num = x 时,票数+1 , num != x 时,票数-1
votes += x == num ? 1 : -1;
}
return x;
}
加入验证众数代码
public int majorityElement(int[] nums) {
int x = 0, votes = 0, count = 0;
for(int num : nums){
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
// 验证 x 是否为众数
for(int num : nums)
if(num == x) count++;
return count > nums.length / 2 ? x : 0; // 当无众数时返回 0
}