1 Two Sum
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.
1 | Example: |
Problem Analysis
Since we need to get the indices of numbers in the original array, we can not sort this array. So, what I am going to do, is to store the result and its index in a map.
Algorithm Analysis
Go through the whole array, check if we can find the current number storing in the Map. If not, we store the number of target - current number and the current index in the map. So, in this map, the key will be target - current number
and the value will be index of the current number.
If we find the current number in the map, we store those two indices into the result static array. Put the index stored in the map at first and the current index for the second one.
Time Complexity Analysis
- Time: O(N)
- Space: O(N)
Code Implementation
1 | class Solution { |
Follow up Question
Do not use additional space.
If we can assume the array was sored, then we can just use two pointers to find the answer.
1 | class Solution { |