Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ba7cfff

Browse files
committedAug 27, 2024
feat: two sum 문제풀이 추가
1 parent d2aa85f commit ba7cfff

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
 

‎two-sum/hwanmini.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// 시간복잡도 O(n log n)
2+
// 공간복잡도 O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @param {number} target
7+
* @return {number[]}
8+
*/
9+
var twoSum = function(nums, target) {
10+
11+
12+
const numsArr = nums.map((num,idx) => [num,idx])
13+
numsArr.sort((a,b) => a[0] - b[0])
14+
15+
16+
let leftIdx = 0;
17+
let rightIdx = nums.length - 1;
18+
19+
while (leftIdx <= rightIdx) {
20+
if (numsArr[leftIdx][0] + numsArr[rightIdx][0] === target) {
21+
return [numsArr[leftIdx][1], numsArr[rightIdx][1]]
22+
}
23+
24+
if (numsArr[rightIdx][0] + numsArr[leftIdx][0] > target) {
25+
rightIdx--
26+
} else {
27+
leftIdx++
28+
}
29+
}
30+
return []
31+
};
32+
33+
34+
const nums = [2,7,11,15]
35+
const target = 9
36+
37+
console.log(twoSum(nums,target))
38+
console.log(twoSum([3,2,4],6))
39+
console.log(twoSum([3,3],6))

0 commit comments

Comments
 (0)
Please sign in to comment.