解法1
多数元素重复次数大于一半,多数投票,最终ans至少多出现一次
class Solution {
public int majorityElement(int[] nums) {
int ans = nums[0], cnt = 1;
for(int i = 1; i < nums.length; i++) {
if (ans == nums[i]) {
cnt++;
} else {
cnt--;
if (cnt < 0) {
ans = nums[i];
cnt = 1;
}
}
}
return ans;
}
}
解法2
哈希表,统计每个数字出现次数,返回出现次数大于一半的数字。
class Solution {
public int majorityElement(int[] nums) {
int threshold = nums.length / 2;
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int cnt = map.getOrDefault(num, 0) + 1;
map.put(num, cnt);
if (cnt > threshold) {
return num;
}
}
return 0;
}
}
解法3
出现次数大于一半,那么,该数字一定会出现在排序后的数组中间位置
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length >> 1];
}
}