Skip to content

Commit 2e9b5fe

Browse files
committed
two sum solution
1 parent 0e5ffe5 commit 2e9b5fe

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

two-sum/ykim7.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// input: array of integers [2,7,11,5], integer 9
2+
// output: indices [0,1]
3+
4+
// 모든 배열의 쌍을 확인하면 시간복잡도가 O(n * n)이 됨.
5+
// 배열의 요소와 인덱스를 함께 저장.
6+
7+
var twoSum = function (nums, target) {
8+
const indices = {};
9+
for (let i = 0; i < nums.length; i++) {
10+
indices[nums[i]] = i;
11+
}
12+
13+
for (let i = 0; i < nums.length; i++) {
14+
let remainder = target - nums[i];
15+
if (indices[remainder] !== undefined && indices[remainder] !== i) {
16+
return [i, indices[remainder]];
17+
}
18+
}
19+
};
20+
21+
// Time Complexity: O(n) + O(n) = O(n)
22+
// Space Complexiy: O(n)

0 commit comments

Comments
 (0)