|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +/** |
| 5 | + * |
| 6 | + * Created by sunmit9 on 30/03/17. |
| 7 | + * |
| 8 | + * https://leetcode.com/problems/two-sum |
| 9 | + * |
| 10 | + * Given an array of integers, return indices of the two numbers such that they add up to a specific target. |
| 11 | + * You may assume that each input would have exactly one solution, and you may not use the same element twice. |
| 12 | + * |
| 13 | + * Given nums = [2, 7, 11, 15], target = 9, |
| 14 | + * Because nums[0] + nums[1] = 2 + 7 = 9, |
| 15 | + * return [0, 1]. |
| 16 | + * |
| 17 | + */ |
| 18 | +public class TwoSum { |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + int[] sol = twoSum(new int[]{2,7,11,15}, 9); |
| 22 | + System.out.println(sol[0] + ", " + sol[1]); |
| 23 | + } |
| 24 | + |
| 25 | + public static int[] twoSum(int[] numbers, int target) { |
| 26 | + int[] result = new int[2]; |
| 27 | + Map<Integer, Integer> map = new HashMap<>(); |
| 28 | + for (int i = 0; i < numbers.length; i++) { |
| 29 | + map.put(numbers[i], i ); |
| 30 | + int complement = target - numbers[i+1]; |
| 31 | + if (map.containsKey(complement)) { |
| 32 | + result[1] = i + 1; |
| 33 | + result[0] = map.get(complement); |
| 34 | + return result; |
| 35 | + } |
| 36 | + } |
| 37 | + return result; |
| 38 | + } |
| 39 | + |
| 40 | + public int[] twoSums(int[] numbers, int target) { |
| 41 | + int[] result = new int[2]; |
| 42 | + Map<Integer, Integer> map = new HashMap<Integer, Integer>(); |
| 43 | + for (int i = 0; i < numbers.length; i++) { |
| 44 | + if (map.containsKey(target - numbers[i])) { |
| 45 | + result[1] = i; |
| 46 | + result[0] = map.get(target - numbers[i]) - 1; |
| 47 | + return result; |
| 48 | + } |
| 49 | + map.put(numbers[i], i + 1); |
| 50 | + } |
| 51 | + return result; |
| 52 | + } |
| 53 | +} |
0 commit comments