I have an array of numbers from 0 to the length of array, except that some number is missing and I have to find it.
public static Integer findNumber(Integer[] array){
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(Integer number : array){
map.put(number, 1);
}
for(Integer i=0; i<array.length; i++){
if(map.get(i)==null)
return i;
}
return -1;
}
I thought this was gonna be a good solution, but putting takes a really long time, sorting solution with counting duplicates is a lot faster, and I have no idea why. Hash for Integer is that Integer itself, so there's not even time lost on counting hash, and no iterating with equals (that depends on numbers, I picked an example with only a single duplicate). I feel like I'm missing something obvious here. I tried specifying initial capacity and load factor, but it only makes things worse. Can I optimize this somehow?
It's putting that takes a lot of time, not iterating over to find solution, putting is like 95% of the time of execution.