Skip to content

Commit c3c3152

Browse files
committed
[leet] two sum (easy)
1 parent 6650fa1 commit c3c3152

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

허현빈/6주차/260202-1.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function(nums, target) {
7+
const map = new Map()
8+
9+
for(let i = 0; i < nums.length; i++){
10+
map.set(nums[i], i);
11+
}
12+
13+
for(let i = 0; i < nums.length; i++){
14+
const val = nums[i];
15+
const complement = target - val;
16+
17+
if(map.has(complement) && map.get(complement) !== i){
18+
return [i, map.get(complement)];
19+
}
20+
}
21+
};

허현빈/6주차/260202-2.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function(nums, target) {
7+
const indexedNums = nums.map((val, idx) => ({ val, idx }));
8+
9+
indexedNums.sort((a, b) => a.val - b.val);
10+
11+
let left = 0;
12+
let right = nums.length - 1;
13+
14+
while (left < right) {
15+
const sum = indexedNums[left].val + indexedNums[right].val;
16+
17+
if (sum === target) {
18+
return [indexedNums[left].idx, indexedNums[right].idx];
19+
} else if (sum < target) {
20+
left++;
21+
} else {
22+
right--;
23+
}
24+
}
25+
};

0 commit comments

Comments
 (0)