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
Output: index1=1, index2=2
这道题还蛮经典的,遇见好多次,还有很多变型,例如more than one solution, return all the pairs.
1. brute force. O(n2)
2. sort then apply two pointer algorithm. O(nlogn) + O(n)
3. hashtable, time complexity O(n), space complexity O(n)
code:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
int[] result = {-1, -1};
for(int i = 0; i < numbers.length; i++){
// if target - numbers[i] exists in table
int pair = target - numbers[i];
if(table.containsKey(pair)){
result[0] = table.get(pair) + 1;
result[1] = i + 1;
return result;
}
else{
table.put(numbers[i], i);
}
}
return result;
}
}
No comments:
Post a Comment