给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。java
你能够假设每种输入只会对应一个答案。可是,你不能重复利用这个数组中一样的元素。数组
示例:bash
给定 nums = [2, 7, 11, 15], target = 9 由于 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
class Solution { public int[] twoSum(int[] nums, int target) { // 暴力搜索,嵌套for循环判断每一个数相加是否等于target // int[] result = new int[2]; // for (int i=0; i<nums.length; i++) { // for(int j=nums.length-1; j>i; j--) { // if(nums[i] + nums[j] == target) { // result[0] = i; // result[1] = j; // return result; // } // } // } // return result; // 使用Map作记录,取出第一个数放到f中 int f = nums[0]; Map<Integer, Integer> dict = new HashMap<>(); // 从nums的第二个数开始循环 for (int i = 1; i < nums.length; i++) { // 判断f和nums[i]中的数相加等于target,返回下标。 if (nums[i] + f == target) { return new int[]{0, i}; } // 计算出nums[i]须要的数组r,想法是target = nums[i] - r int r = target - nums[i]; // 判断r是否在map中,若是在,就说明找到了nums[i]与r(map中存放的是r的索引) if (dict.containsKey(r)) { return new int[]{dict.get(r), i}; } // 若是不在,将nums[i]和索引放入map,等到target - r = nums[i]的时机 dict.put(nums[i], i); } return null; } }
暴力搜索的时间复杂度和空间复杂度分别是:O(n^2)和O(1);spa
Map记录的时间复杂度和空间复杂度都是:O(n);code