/*** * 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]. * */
public class N001_TwoSum { /*** * 暴力搜索 时间复杂度是o(n2) ,舍弃 * * hashmap是常数级的查找效率 * 这样咱们在遍历数组的时候,用target减去遍历到的数字,就是另外一个须要的数字了,直接在HashMap中查找其是否存在便可 * 注意要判断查找到的数字不是第一个数字 */ public static int[] find(int[] nums, int target) { HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); int[] res = new int[2]; for (int i = 0; i < nums.length; ++i) { if (m.containsKey(target - nums[i])) { res[0] = m.get(target - nums[i]); res[1] = i; // 此时 i 对应的元素尚未放进去。 return res; } m.put(nums[i], i); } return res; } public static void main(String args[]) { int target = 14; int[] nums = {2, 7, 11, 15}; int[] result = find(nums, target); for (int num : result) { System.out.println(num); } } }