Problem:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution:
import java.util.*;
class Solution {
public static void main(String...args) {
int[] a = new int[]{3, 4, 1, -4, 5, -2};
int sum = 0;
int[] s = twoSum(a, sum);
if(s == null) {
System.out.println("no solution");
} else {
System.out.println("[" + s[0] + "," + s[1] + "]");
}
}
//time: O(N), space O(N)
public static int[] twoSum(int[] a, int sum) {
int N = a.length;
Map<Integer, Integer> visited = new HashMap<>();
for(int i = 0; i < N; i++) {
Integer index = visited.get(sum - a[i]);
if(index != null) {
int[] hit = new int[2];
hit[0] = index;
hit[1] = i;
return hit;
}
visited.put(a[i], i);
}
return null;
}
}