Skip to content

Commit abe5952

Browse files
committed
two-sum solved
1 parent 25ad7df commit abe5952

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

two-sum/kut7728.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
3+
class Solution {
4+
// 복잡도 O(n^2)
5+
// func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
6+
// for (i, num) in nums.enumerated() {
7+
// guard let tempIndex = nums.firstIndex(of: target - num) else {continue}
8+
// if tempIndex == i { continue }
9+
// return [i, tempIndex]
10+
// }
11+
// return [0]
12+
// }
13+
14+
// 시간, 공간 복잡도 O(n)
15+
// 해쉬맵 사용하기!
16+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
17+
var list: [Int:Int] = [:]
18+
for (i, num) in nums.enumerated() {
19+
if let exist = list[target-num] {
20+
return [exist, i]
21+
} else {
22+
list[num] = i
23+
}
24+
}
25+
return [0]
26+
27+
28+
}
29+
}

0 commit comments

Comments
 (0)