Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
给出目标target,找到数组中相加等于target的两元素的下标
此题在我们脑中最先想到的思路是两重循环,找到所有组合,时间复杂度为O(n2),但是然并卵,这显然不是面试官想要的解法
比较有技巧性的解法,是用HashMap,key是数组元素,value是数组下标,这样只需要遍历一次就可以,时间复杂度O(n)
这道题解的好的话,印象分+10
1 public int[] twoSum(int[] nums, int target) { 2 3 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 4 int[] result = new int[2]; 5 for (int i = 0; i < nums.length; i++) { 6 if (map.get(target - nums[i]) == null) { 7 map.put(nums[i], i); 8 } else { 9 result[0] = map.get(target - nums[i]) + 1; 10 result[1] = i + 1; 11 } 12 } 13 return result; 14 }