Question:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Solution:
1. O(n2) runtime, O(1) space – Brute force:
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).
2. O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
int[] result = new int[2];
int length = nums.length;
for (int i = 0; i < length; i++) {
int left = target - nums[i];
if (hm.get(left) != null) {
result[0] = hm.get(left) + 1;
result[1] = i + 1;
} else {
hm.put(nums[i], i);
}
}
return result;
}
}
3. O(nlogn) runtime, O(1) space - Binary search
Similar as solution 1, but use binary search to find index2.
4. O(nlogn) runtime, O(1) space - Two pointers
First, sort the array in ascending order vwhich uses O(nlogn).
Then, right pointer starts from biggest number and left pointer starts from smallest number. If two sum is greater than the target number, move the right pointer. If two sum is smaller than the target number, move the left pointer.