題目地址:https://leetcode-cn.com/problems/two-sum/java
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個整數,並返回他們的數組下標。數組
你能夠假設每種輸入只會對應一個答案。可是,數組中同一個元素不能使用兩遍。緩存
示例:指針
輸入:nums = [2, 7, 11, 15], target = 9 輸出:[0, 1] 由於 nums[0] + nums[1] = 2 + 7 = 9
這裏想必你們很快就能獲得思路也就是雙指針遍歷全部兩兩相加判斷是否與目標值相等code
public int[] twoSum(int[] nums, int target) { int n = nums.length; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[0]; }
但實際上按照上面咱們去到數組當中找兩個數相加爲目標值的方式也就是在肯定nums[i]的狀況下與遍歷找target - nums[i].既然是這樣子那咱們直接遍歷一次記下全部的target-nums[i]再看數組當中存在taget-nums[i]不。若存在即返回下標爲i與taget-nums[i]這個值的下標。那麼咱們就使用hash表去記錄數組值爲key下標爲valueleetcode
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0]; }
前者比起哈希表的解法未添加緩存信息所以須要花O(n^2)的時間複雜度來匹配,採用hash表記錄增長了空間消耗時間複雜度O(n)由於配對的過程轉爲hash表查找。get