// 自己的笨比方法,用hashMap存,又慢又费内存
class Solution {
public int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
Map<Integer, Integer> map = new HashMap<>();
for (int a : nums) {
if (map.containsKey(a)) {
map.put(a, map.get(a) + 1);
} else {
map.put(a, 1);
}
if (map.get(a) > nums.length / 2) {
return a;
}
}
return -1;
}
}
// 别人的摩尔投票法,又快又省内存
class Solution {
public int majorityElement(int[] nums) {
// 摩尔投票法 众数-其他 >=1 所以留下来的一定是众数
int n = 0, times = 0;
for (int i = 0; i < nums.length; i++) {
if (times == 0) {
n = nums[i];
times = 1;
} else if (n == nums[i]) {
times++;
} else {
times--;
}
}
return n;
}
}