题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 // 1. 暴力,两遍遍历 4 // for (int i = 0; i < nums.length; i++) { 5 // for (int j = i + 1; j < nums.length; j++) { 6 // if (nums[i] + nums[j] == target) { 7 // return new int[] {i ,j}; 8 // } 9 // } 10 // } 11 // return new int[0]; 12 13 // 2. 双层哈希 14 // Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 15 // for (int i = 0; i < nums.length; i++) { 16 // map.put(nums[i], i); 17 // } 18 // for (int i = 0; i < nums.length; i++) { 19 // int complement = target - nums[i]; 20 // if (map.containsKey(complement) && map.get(complement) != i) { 21 // return new int[]{i, map.get(complement)}; 22 // } 23 // } 24 // return new int[0]; 25 26 // 3. 一层哈希 27 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 28 for (int i = 0; i < nums.length; i++) { 29 int complement = target - nums[i]; 30 // 关于这一步,i的那个肯定是不包含的,因为是走到i这边还没put到map里 31 // if (map.containsKey(nums[i]) && map.containsKey(complement) && i != map.get(complement)) { 32 if (map.containsKey(complement) && i != map.get(complement)) { 33 // 应该是i后出现,所以i应该在后面 34 // return new int[]{i, map.get(complement)}; 35 return new int[]{map.get(complement), i}; 36 } 37 map.put(nums[i], i); 38 } 39 return new int[0]; 40 41 // 最后我都是直接return了一个没有意义的数组,官方是直接throw new IllegalArgumentException("No two sum solution"); 42 } 43 }
原文:https://www.cnblogs.com/utomboy/p/13564080.html