Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
public class Solution {
public int majorityElement(int[] nums) {
Map map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int count = (int) map.get(nums[i])+1;
map.put(nums[i], count);
}
else {
map.put(nums[i],1);
}
}
int key=0,val=0;
//遍历hashmap
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()){
//Map.Entry entry = (Entry) iterator.next();
key = (int) iterator.next();
val = (int) map.get(key);
if(val > nums.length/2) return key;
}
return 0;
}
}