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.
The differences between
- Hashtable is synchronized, but HashMap is not. So for non-threaded applications, here using
HashMapis better since unsynchronized object perform better for this situation.
Hashtabledoes not allow either
nullkey or value, but
nullkey and unlimited number of
- In case you want to preserve some iteration order of the
HashMap, you can easily cast to
LinkedHashMap, which may be difficult if you use
- In case you want synchronization with