Problem
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
1 |
|
Explanation
-
We can use a HashMap to solve this problem because HashMap uses $O(1)$ to find the key.
-
Iterate the array, store the element as key, index as value. But before we store, we first check if the map contains the element we want to find, which is
target - nums[i]
. If the map already have this value we want to find, then we can return the result with current index andmap.get(target-nums[i])
.
Solution
1 |
|