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.
publicint[] twoSum(int[] numbers, int target) { Map<Integer, Integer> m = new HashMap<Integer, Integer>();// num => index
Integer[] result = new Integer[2]; for (int i = 0; i < numbers.length; i++) { if (target % 2 == 0 && numbers[i] == target / 2) { if (result[0] == null) { result[0] = i + 1; } else { result[1] = i + 1; returnnewint[]{result[0], result[1]}; } continue; } m.put(numbers[i], i); }
for (int num : m.keySet()) { if (m.containsKey(target - num)) { int a = m.get(num) + 1; int b = m.get(target - num) + 1; return a > b ? newint[]{b, a} : newint[]{a, b}; } } returnnull; }
publicint[] twoSum(int[] numbers, int target) { int[] a = newint[2]; Map<Integer, Integer> nums = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { //put number into hash table (if it's not already there) Integer n = nums.get(numbers[i]); if (n == null) nums.put(numbers[i], i); //subtract array element from target number n = nums.get(target - numbers[i]); if (n != null && n < i) {//if such number exists in the table return the indicies a[0] = n + 1; a[1] = i + 1; return a; } } return a; }