Skip to content

Commit 15e1e14

Browse files
committed
feat: 1. Two Sum
1 parent 4c8b68f commit 15e1e14

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

two-sum/gwbaik9717.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time complexity: O(nlogn)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @param {number} target
7+
* @return {number[]}
8+
*/
9+
var twoSum = function (nums, target) {
10+
const n = nums.length;
11+
12+
const mappedNums = nums.map((num, i) => [num, i]);
13+
mappedNums.sort((a, b) => a[0] - b[0]);
14+
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;
24+
}
25+
26+
if (sum < target) {
27+
left++;
28+
continue;
29+
}
30+
31+
return [mappedNums[left][1], mappedNums[right][1]];
32+
}
33+
};

0 commit comments

Comments
 (0)