给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
class Solution {
public static int majorityElement(int[] nums) {
//定义好大于一半的数字大小
int pos = nums.length/2+1;
int max = Integer.MIN_VALUE;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i <= nums.length - 1; i++) {
//getOrDefault()解释:map中有值则返回value,第一次存该key则返回0;
Integer count = map.getOrDefault(nums[i], 0);
map.put(nums[i], ++count);
}
Set<Integer> keySet = map.keySet();
//遍历keySet,找出存储的value(也就是出现的次数,众数)大于一半的那个key
for (Integer key : keySet) {
if (map.get(key) >= pos) {
return key;
}
}
return -1;
}
}