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.
Credits:
Special thanks to
@ts for adding this problem and creating all test cases.
import java.util.HashMap;
public class Solution {
public int majorityElement(int[] num) {
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
for(int i=0;i<num.length;i++){
hm.put(num[i],hm.containsKey(num[i])?hm.get(num[i])+1:1);
}
System.out.println(hm.entrySet());
int x=0,tag=0;
for(Integer kk:hm.keySet()){
if(hm.get(kk)>x){
x=hm.get(kk);
tag=kk;
}
}
return tag;
}
}
其中那個foreach循環可以使用迭代器iterator()實現
for(Iterator itr = hm.keySet().iterator(); itr.hasNext();){
int key = (Integer) itr.next();
if(hm.get(key)>x){
x=hm.get(kk);
tag=kk;;
}
}