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].
Approach 1
public class TwoSums {
@Test
public void test () {
Assert.assertArrayEquals(new int[] {0,1}, twoSum(new int[]{2,7,11,15}, 9));
Assert.assertArrayEquals(new int[] {1,2}, twoSum(new int[]{3,2,4}, 6));
}
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == target - nums[j]) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
Approach 2
public class TwoSums {
@Test
public void test () {
Assert.assertArrayEquals(new int[] {0,1}, twoSum(new int[]{2,7,11,15}, 9));
Assert.assertArrayEquals(new int[] {1,2}, twoSum(new int[]{3,2,4}, 6));
}
public int[] twoSum(int[] nums, int target) {
AtomicInteger integer = new AtomicInteger(0);
Map<Integer, Integer> collect = Arrays.stream(nums).boxed().collect(Collectors.toMap(Function.identity(), o -> integer.getAndIncrement()));
for (Map.Entry<Integer, Integer> entry : collect.entrySet()) {
Integer first = entry.getKey();
if (collect.containsKey(target - first)) {
return new int[] {collect.get(first),collect.get(target-first)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}