Leetcode 001: Two Sum


Leetcode 001: Two Sum


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 and HashMap:

  1. 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.
  2. Hashtable does not allow either null key or value, but HashMap allows one null key and unlimited number of null values.
  3. 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 Hashtable.
  4. In case you want synchronization with HashMap, try ConcurrentHashMap.