Skip to content

Commit 3627b22

Browse files
committed
two sum: refactoring
1 parent 39dd8e3 commit 3627b22

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

two_sum/main.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
function twoSum(numbers, target) {
2+
/// This for loop has a time complexity of O(n).
3+
const seen = new Map();
4+
for(let i = 0; i < numbers.length; i++) {
5+
let value = numbers[i], sub = target - numbers[i];
6+
if(seen.has(sub)) return [seen.get(sub), i];
7+
seen.set(value, i);
8+
}
9+
10+
/// This for loop has a time complexity of O(n^2).
211
for(let i = 0; i < numbers.length - 1; i++) {
312
let sub = target - numbers[i];
413
for(let j = i + 1; j < numbers.length; j++) {

0 commit comments

Comments
 (0)