Skip to content

Commit 2d73efd

Browse files
committed
Refactor two-sum
1 parent b86951e commit 2d73efd

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

two-sum/sooooo-an.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
function twoSum(nums: number[], target: number): number[] {
2+
const visited: { [key: string]: boolean } = {};
23
for (let i = 0; i < nums.length; i++) {
3-
for (let j = i + 1; j < nums.length; j++) {
4-
if (nums[i] + nums[j] === target) {
5-
return [i, j];
6-
}
4+
const complement = target - nums[i];
5+
if (visited[complement]) {
6+
const complementIdx = nums.indexOf(complement);
7+
return [i, complementIdx];
78
}
9+
visited[nums[i]] = true;
810
}
11+
return [];
912
}
1013

1114
/**
12-
* runtime: 30ms / Beats 38.67%
13-
* memory 56.56MB / Beats 63.38%
15+
* runtime: O(n)
16+
* memory O(n)
1417
*/

0 commit comments

Comments
 (0)