数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
用过较多方法,后认为比较好的解法:
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int e : nums)
{
int count = map.getOrDefault(e, 0) + 1;
map.put(e, count);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet())
{
if (entry.getValue() > nums.length / 2)
{
return entry.getKey();
}
}
return -1;
}
}
getOrDefault方法举例
Map<Integer,String> map = new HashMap<>();
map.put(1,"我是一");
// 存在Key1,返回11
System.out.println(map.getOrDefault(1,"我是一"));
// 不存在Key3,返回默认值33
System.out.println(map.getOrDefault(3,"我是三"));