Skip to content

Commit 6629a0e

Browse files
committed
sadie100: two sum solution
1 parent 1fca640 commit 6629a0e

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

two-sum/sadie100.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
풀이
3+
nums를 값과 index가 있는 객체 배열 newNums로 재정의한다
4+
newNums를 값 오름차순으로 정렬하고 두 포인터 start, end를 둔다
5+
nums[start] + nums[end]가 target보다 작으면 start+1하고, target보다 크면 end-1한다. 같으면 nums[start]과 nums[end]의 오리진 index를 리턴한다.
6+
만약 start>=end가 되면 빈 배열을 리턴한다
7+
8+
시간복잡도
9+
O(nLogN) - 정렬. 포인터 순회는 O(N)이므로 최종적으로 O(nLogN)
10+
11+
공간복잡도
12+
O(N) : newNums 배열
13+
*/
14+
15+
function twoSum(nums: number[], target: number): number[] {
16+
const newNums = nums.map((value, idx) => ({ value, idx }))
17+
const sortedNums = newNums.sort((a, b) => a.value - b.value)
18+
let start = 0
19+
let end = nums.length - 1
20+
21+
while (start < end) {
22+
const total = sortedNums[start].value + sortedNums[end].value
23+
if (total === target) {
24+
return [sortedNums[start].idx, sortedNums[end].idx]
25+
} else if (total > target) {
26+
end -= 1
27+
} else {
28+
start += 1
29+
}
30+
}
31+
32+
return []
33+
}

0 commit comments

Comments
 (0)