給定一個整數數組 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