This method returns the number from the array of positive integers if it occurs more than half times of the array size, -1 otherwise. I need to improve its running time for larger arrays (10^5<size<10^8)
. Any suggestions?
public static int findResult(int arr[],int len){
int val=0;
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<len;i++){
if(map.containsKey(arr[i])){
val = (Integer)map.get(arr[i]);
map.put(arr[i], val+1);
}else{
val=1;
map.put(arr[i], val);
}
}
Iterator<Integer> it=map.keySet().iterator();
while(it.hasNext()){
int next=it.next();
if((Integer)map.get(next)>(len/2)){
return next;
}
}
return -1;
}