https://leetcode-cn.com/probl...
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。 你能夠假設每種輸入只會對應一個答案。可是,數組中同一個元素不能使用兩遍。 示例: 給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
首先把加法轉換成減法
而後利用 Map 的數據結構儲存 target 減去某一位置的值和位置 i 對應
接着判斷若是減出的值在 Map 結構中找到則跳出循環,不然將對於的減出來的值和數組的索引 i 對應儲存
最後返回兩個索引javascript
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ const twoSum = function (nums, target) { const map = new Map(); const len = nums.length; //數組長度 for (let i = 0; i < len; i++) { //遍歷查找數組nums let diff = target - nums[i]; //target減去對應的數組的值 if (map.has(diff)) { //判斷是否已存在對應的減值,存在則取出返回,不然將減值(減出來的值)和對應索引儲存 return [map.get(diff), i]; } map.set(nums[i], i); //將減值(減出來的值)和對應索引儲存 } };
將 obj 替換 Map 去解決問題java
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ const twoSum1 = function (nums, target) { const obj = {}; const len = nums.length; for (let i = 0; i < len; i++) { let I = nums[i]; let j = target - I]; if (obj[j] !== undefined) { return [obj[j], i]; } obj[I] = i; } };
遍歷解法git
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ const twoSum2 = function (nums, target) { const len = nums.length; for (let i = 0; i < len; i++) { for (let j = i + 1; j < len; j++) { if (nums[i] + nums[j] === target) { return [i, j]; } } } };
須要 try catch,扔出 error 纔會直接返回,github
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ const twoSum3 = function (nums, target) { const hash = {}; let result = []; try { nums.map(function (val, i) { let reduce = target - val; if (hash[reduce] !== undefined) { result[0] = hash[reduce]; result[1] = i; throw "err"; } hash[val] = i; }); } catch (err) { return result; } };
github地址數組