给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。html
你能够假设每种输入只会对应一个答案。可是,你不能重复利用这个数组中一样的元素。数组
给定 nums = [2, 7, 11, 15], target = 9优化
由于 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]spa
暴力法很简单,遍历每一个元素 x,并查找是否存在一个值与 target − x 相等的目标元素。code
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 (nums[j] == target - nums[i]) { return new int[]{i, j}; } } } throw new IllegalArgumentException("No two sum solution"); } }
利用HashMap 减小查询时间htm
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<>(); int[] res = new int[2]; for (int i = 0; i < nums.length; i++) { int dif = target - nums[i]; if (map.get(dif) != null) { res[0] = map.get(dif); res[1] = i; return res; } map.put(nums[i],i); } return res; } }
public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap(); for (int i = 0; i < nums.length; ++i) { if (map.containsKey(target- nums[i])) { return new int[]{map.get(target- nums[i]), i}; } map.put(nums[i], i); } return int[]{-1, -1}; } }
看到这个题,第一个想到的就是暴力法,确实作出来了,发现时间复杂度和空间复杂度都挺高的,hashMap的时间复杂度远远低于暴力法,算是用空间换时间的一种方法了。blog
代码优化之后尽量的去作,话说讨论区好多大佬啊。get