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
先来一个超时的暴力算法:
- public class Solution {
- public int[] twoSum(int[] numbers, int target) {
- int[] res = new int[2];
- for (int i = 0; i < numbers.length-1; i++){
- for (int j = i+1; j < numbers.length; j++){
- if(numbers[i] + numbers[j] == target){
- res[0] = i+1;
- res[1] = j+1;
- return res;
- }
- }
- }
- return res;
- }
- }
two sum 和之后的 three sum 以及 4 sum 都简单了许多,这里的解法是吧 所有 numbers 中的元素以及他们所对应的 1-based index 关系存储在 map 中,
然后遍历整个数组,确立一个 index ,找 target - numbers[ i ] 的 index ,找到就是结果。
这题不能用 sort 解决 sum3 sum4 的方法, 因为题目要求返回的是原数组的 index
- //use hashmap hash all element in that array, then find if the map contains target - numbers[i]
- public class Solution {
- public int[] twoSum(int[] numbers, int target) {
- if (numbers == null || numbers.length < 2){
- return null;
- }
- int[] res = new int[2];
- Map<Integer, Integer> map = new HashMap<>();
- for (int i = 0; i < numbers.length; i++){
- map.put(numbers[i], i+1); // 保存 元素和 index 关系(index 转换成1 base )
- }
- for (int i = 0; i < numbers.length-1 ; i++){
- if (map.containsKey(target-numbers[i])){
- int index1 = i+1;
- int index2 = map.get(target-numbers[i]);
- if (index1 == index2){
- continue;
- }
- res[0] = index1;
- res[1] = index2;
- return res;
- }
- }
- return res;
- }
- }