From 38f5c25ed4aa18c72c82a484f4500a3188d02e30 Mon Sep 17 00:00:00 2001 From: kody <809478662@qq.com> Date: Mon, 21 May 2018 11:21:46 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=86=E4=BA=AB=E4=B8=80=E4=B8=AA=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6=E4=B8=BAO(1)=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- solutions/0001 Two Sum/1 Two Sum.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/solutions/0001 Two Sum/1 Two Sum.js b/solutions/0001 Two Sum/1 Two Sum.js index a97e562..e87e44b 100644 --- a/solutions/0001 Two Sum/1 Two Sum.js +++ b/solutions/0001 Two Sum/1 Two Sum.js @@ -21,4 +21,22 @@ var twoSum = function (nums, target) { }) return result; }; -console.log(twoSum([1, 3, 4], 7)); \ No newline at end of file +console.log(twoSum([1, 3, 4], 7)); + +const twoSum1 = (nums, target) => { + // target 不能大于等于 Number.MAX_SAFE_INTEGER + // 时间复杂度 O(n) + // 空间复杂度 O(1) + let firstNum = null; + let secondNumIndex = -1; + for (let i = 0; i < nums.length; i += 1) { + firstNum = nums[i]; + nums[i] = Number.MAX_SAFE_INTEGER; + secondNumIndex = nums.indexOf(target - firstNum); + if (secondNumIndex > -1) { + return [i, secondNumIndex]; + } + nums[i] = firstNum; + } + return [-1, -1]; +} \ No newline at end of file