Skip to content

Commit 8d84daf

Browse files
committed
two-sum solution
1 parent f1e8a69 commit 8d84daf

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

two-sum/togo26.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
/*
8+
TC: O(n)
9+
SC: O(n) -> Map 사용
10+
*/
11+
12+
var twoSum = function (nums, target) {
13+
const map = new Map();
14+
for (let i = 0; i < nums.length; i++) {
15+
const complement = target - nums[i];
16+
if (map.has(complement)) return [map.get(complement), i];
17+
map.set(nums[i], i);
18+
}
19+
};
20+
21+
/*
22+
With two points
23+
TC: O(nlogn) -> sort 사용
24+
SC: O(n) -> origin index 배열 생성
25+
*/
26+
27+
var twoSum = function (nums, target) {
28+
const numsWithOriginIndex = nums.map((num, i) => [num, i]);
29+
numsWithOriginIndex.sort(([a], [b]) => a - b);
30+
31+
let left = 0;
32+
let right = nums.length - 1;
33+
let result;
34+
35+
while (left < right) {
36+
const [leftValue, leftIndex] = numsWithOriginIndex[left];
37+
const [rightValue, rightIndex] = numsWithOriginIndex[right];
38+
const sum = leftValue + rightValue;
39+
40+
if (sum === target) {
41+
result = [leftIndex, rightIndex];
42+
break;
43+
}
44+
45+
if (sum > target) right--;
46+
else left++;
47+
}
48+
49+
return result;
50+
};
51+
52+
/*
53+
Brute force
54+
TC: O(n^2)
55+
SC: O(1)
56+
*/
57+
58+
var twoSum = function (nums, target) {
59+
for (let i = 0; i < nums.length; i++) {
60+
for (let j = i + 1; j < nums.length; j++) {
61+
if (nums[i] + nums[j] === target) {
62+
return [i, j];
63+
}
64+
}
65+
}
66+
return result;
67+
};

0 commit comments

Comments
 (0)