Problem
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
1 2 3 4 |
public static int[] twoSum(int[] numbers, int target) { } |
Solution 1 – using HashMap
Analysis: O(n) runtime, O(n) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public static int[] twoSum(int[] numbers, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); // value and index for(int i = 0; i < numbers.length; i++) { map.put(numbers[i], i); } int idxs[] = new int[2]; for(int i = 0; i < numbers.length -1; i++) { int balance = target - numbers[i]; if(map.containsKey(balance)) { if(map.get(balance) == i) continue; idxs[0] = i + 1; idxs[1] = map.get(balance) +1; break; } } return idxs; } |
Solution 2 – Brute force
Save the numbers in the set. Scan the numbers: pick one number #1, if the balance (target – #1) is in the set, then another number (#2) exists. Scan the rest numbers to find the index of #2.
Analysis: O(n2) runtime, O(n) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public int[] twoSum(int[] numbers, int target) { Set<Integer> set = new HashSet<Integer>(); // # and index for(Integer val : numbers) { set.add(val); } int idxs[] = new int[2]; for(int i = 0; i < numbers.length -1; i++) { int balance = target - numbers[i]; if(set.contains(balance)) { idxs[0] = i; // find another index for(int k = i + 1; k < numbers.length; k++) { if(balance == numbers[k]) { idxs[1] = k; return idxs; } } } } return idxs; } |