输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
方法一:哈希表统计法
class Solution {
public 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>>1) return num;
}
return 0;
}
}
方法二:排序取中位数
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length>>1];
}
}
方法三:摩尔投票法
class Solution {
public int majorityElement(int[] nums) {
//count:个数,curr:当前假设的众数
int count = 0,curr = 0;
for (int num : nums){
if (count == 0) curr = num;
count += num == curr ? +1 : -1;
}
return curr;
}
}