题目
解答
public void testMajorityElement(){
int[] nums = {2,2,1,1,1,2,2};
System.out.println(majorityElement(nums));
}
private int majorityElement(int[] nums){
Map<Integer,Integer> m = new HashMap<Integer, Integer>();
for(int i = 0;i<nums.length;i++){
if(m.containsKey(nums[i])){
Integer count = m.get(nums[i]);
m.put(nums[i],++count);
}else{
m.put(nums[i],1);
}
}
for(Map.Entry<Integer, Integer> entry : m.entrySet()){
if(entry.getValue()>(nums.length/2)) return entry.getKey();
}
return -1;
}