Skip to content

Commit 2530b0f

Browse files
committed
refactor: feat: 1. Two Sum
1 parent 15e1e14 commit 2530b0f

File tree

1 file changed

+9
-20
lines changed

1 file changed

+9
-20
lines changed

two-sum/gwbaik9717.js

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Time complexity: O(nlogn)
1+
// Time complexity: O(n)
22
// Space complexity: O(n)
33

44
/**
@@ -7,27 +7,16 @@
77
* @return {number[]}
88
*/
99
var twoSum = function (nums, target) {
10-
const n = nums.length;
10+
const map = new Map();
1111

12-
const mappedNums = nums.map((num, i) => [num, i]);
13-
mappedNums.sort((a, b) => a[0] - b[0]);
12+
for (let i = 0; i < nums.length; i++) {
13+
const num = nums[i];
14+
const diff = target - num;
1415

15-
let left = 0;
16-
let right = n - 1;
17-
18-
while (left < right) {
19-
const sum = mappedNums[left][0] + mappedNums[right][0];
20-
21-
if (sum > target) {
22-
right--;
23-
continue;
16+
if (map.has(diff)) {
17+
return [i, map.get(diff)];
18+
} else {
19+
map.set(num, i);
2420
}
25-
26-
if (sum < target) {
27-
left++;
28-
continue;
29-
}
30-
31-
return [mappedNums[left][1], mappedNums[right][1]];
3221
}
3322
};

0 commit comments

Comments
 (0)