Skip to content

Commit 89cf4e9

Browse files
author
easyone
committed
Feat: Add solution of two-sum.
1 parent 4c8b68f commit 89cf4e9

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

two-sum/easyone-jwlee.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// 풀이
2+
// map의 key에 값, value에 index를 넣어, target-num이 map에 존재할 때를 찾기.
3+
// 오직 하나의 답만 무조건 존재한다고 했기 때문에 찾자마자 return.
4+
5+
// TC
6+
// 가장 마지막 인덱스까지 가서야 값을 구할 수 있었다고 하면, nums의 길이만큼 for문을 한바퀴 돌기때문에 O(n).
7+
8+
// SC
9+
// 중복없이 마지막 인덱스까지 가서 값을 구한다면 들어오는 nums의 길이만큼 map도 공간을 차지하게 되므로 O(n).
10+
11+
func twoSum(nums []int, target int) []int {
12+
m := make(map[int]int)
13+
for i, num := range nums {
14+
if index, ok := m[target-num]; ok {
15+
return []int{index, i}
16+
}
17+
m[num] = i
18+
}
19+
return []int{0, 0}
20+
}

0 commit comments

Comments
 (0)