Skip to content

Commit 5a7f096

Browse files
authored
Create 1-Two-Sum.swift
Swift version of Two Sum. Accepted by Leetcode Judge.
1 parent 933ca4a commit 5a7f096

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

swift/1-Two-Sum.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
3+
var prevMap = [Int:Int]() // val -> index
4+
5+
for (i, n) in nums.enumerated() {
6+
let diff = target - n
7+
if let firstIndex = prevMap[diff] {
8+
return [firstIndex, i]
9+
}
10+
prevMap[n] = i
11+
}
12+
return []
13+
}
14+
}

0 commit comments

Comments
 (0)