题目链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]思路:(1)暴力法,遍历每个元素 x,并查找是否存在一个值与 target−x 相等的目标元素。
class Solution { public int[] twoSum(int[] nums, int target) { for(int i=0; i<nums.length; i++) { for(int j=i+1; j<nums.length; j++) { if(target - nums[i] == nums[j]) return new int[]{i,j}; } } throw new IllegalArgumentException("No two sum solution"); } }(2)hashmap两次迭代
在第一次迭代中,我们将每个元素的值和它的索引添加到表中。
把数值作为 key,把数值所在的下标作为 value然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i]) 是否存在于表中。
注意,该目标元素不能是 nums[i]本身!
用到的函数的意义:
containsKey(Object key) 返回值类型:boolean 如果此映射包含对于指定键的映射关系,则返回 true。 put(K key, V value) 在此映射中关联指定值与指定键。 get(Object key) 返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 null。 class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> hash = new HashMap<Integer, Integer>(); for(int i=0; i<nums.length; i++) { hash.put(nums[i], i); } for(int i=0; i<nums.length; i++) { if(hash.containsKey(target - nums[i]) && hash.get(target - nums[i]) != i) return new int[]{i, hash.get(target - nums[i])}; } throw new IllegalArgumentException("No two sum solution"); } }(3)hashmap一次迭代
在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } }