Skip to content

Commit 65c57e6

Browse files
committed
feat(soobing): two-sum
1 parent f291ae8 commit 65c57e6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

two-sum/soobing.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// 1. Brute force
2+
function twoSum(nums: number[], target: number): number[] {
3+
for (let i = 0; i < nums.length - 1; i++) {
4+
for (let j = i + 1; j < nums.length; j++) {
5+
if (nums[i] + nums[j] === target) {
6+
return [i, j];
7+
}
8+
}
9+
}
10+
return [];
11+
}
12+
13+
// 2. Hashmap
14+
function twoSum(nums: number[], target: number): number[] {
15+
const map = new Map();
16+
for (let i = 0; i < nums.length; i++) {
17+
map.set(nums[i], i);
18+
}
19+
20+
for (let i = 0; i < nums.length; i++) {
21+
const targetIndex = map.get(target - nums[i]);
22+
if (targetIndex && targetIndex !== i) {
23+
return [i, targetIndex];
24+
}
25+
}
26+
return [];
27+
}

0 commit comments

Comments
 (0)