Solution:
Idea:
The solution is to use a hashtable to store the information. The key is the a[i]
‘s value and the value is the index, i.e. i
. Once find some a[i]
that there exists a key equals to target - a[i]
, the index you stored into that key and the current index will be the answer.
Extra:
The differences between Hashtable
and HashMap
:
- Hashtable is synchronized, but HashMap is not. So for non-threaded applications, here using
HashMap
is better since unsynchronized object perform better for this situation. Hashtable
does not allow eithernull
key or value, butHashMap
allows onenull
key and unlimited number ofnull
values.- In case you want to preserve some iteration order of the
HashMap
, you can easily cast toLinkedHashMap
, which may be difficult if you useHashtable
. - In case you want synchronization with
HashMap
, tryConcurrentHashMap
.