Given an array of integers, return indices of the two numbers such that they add up to a specific target.
1 public class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 if (nums == null || nums.length < 2) { 4 return null; 5 } 6 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 7 for (int i = 0; i < nums.length; i++) { 8 int r = target - nums[i]; 9 if (map.containsKey(r)) { 10 return new int[] { map.get(r), i }; 11 } else { 12 map.put(nums[i], i); 13 } 14 } 15 return null; 16 } 17 }

浙公网安备 33010602011771号