import java.util.HashMap;
public class Solution {
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> pair=new HashMap<>();
int result[] = new int[2];
for(int i=0;i<nums.length;i++){
if(pair.containsKey(nums[i])){
result[0]=pair.get(nums[i]);
result[1]=i;
return result;
}
else{
pair.put(targetnums[i], i);
}
}
return result;
}
}
A Java solution in 8ms


@mmccoy37 I don't really understand what you mean, what is we have ?
The complexity of seeking in HashMap is O(1), which is really fast.

This is a very smart solution!
Though, a HashMap look up is NOT guaranteed at O(1) as far as I know.
Hashing is not free either.Regardless, I really like the solution, thank you for sharing!
http://stackoverflow.com/questions/4553624/hashmapgetputcomplexity
http://stackoverflow.com/questions/1055243/isajavahashmapreallyo1

@plover I think he meant 'WE HAVE' as the numbers that we have iterated:)
BTW, is the complexity of putting in HashMap is O(1)?


@ZengRed Not really. It depends on the implementation of HashMap. If there are many elements whose hash value is the same, then the complexity is more complicated. Thanks @exkor5000 for providing some infomation about hashmap !