Skip to content

Commit 4850651

Browse files
distressedrookAvismara Hugoppalu
andauthored
feat: add a Two Sum solution in Swift language (doocs#473)
* add a Two Sum solution in Swift language * update README_EN to include the swift solution to 0001.Two Sum Co-authored-by: Avismara Hugoppalu <avismara@campus.build>
1 parent cff0890 commit 4850651

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

solution/0000-0099/0001.Two Sum/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,29 @@ var twoSum = function (nums, target) {
108108
};
109109
```
110110

111+
### **Swift**
112+
113+
```swift
114+
class Solution {
115+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
116+
var map = [Int: Int]()
117+
var i = 0
118+
for num in nums {
119+
map[num] = i
120+
i = i + 1
121+
}
122+
i = 0
123+
for num in nums {
124+
if let otherIndex = map[target - num], otherIndex != i {
125+
return [i, otherIndex]
126+
}
127+
i = i + 1
128+
}
129+
return []
130+
}
131+
}
132+
```
133+
111134
### **...**
112135

113136
```

solution/0000-0099/0001.Two Sum/README_EN.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,28 @@ var twoSum = function (nums, target) {
9393
return [];
9494
};
9595
```
96+
### **Swift**
9697

98+
```swift
99+
class Solution {
100+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
101+
var map = [Int: Int]()
102+
var i = 0
103+
for num in nums {
104+
map[num] = i
105+
i = i + 1
106+
}
107+
i = 0
108+
for num in nums {
109+
if let otherIndex = map[target - num], otherIndex != i {
110+
return [i, otherIndex]
111+
}
112+
i = i + 1
113+
}
114+
return []
115+
}
116+
}
117+
```
97118
### **...**
98119

99120
```
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
3+
var map = [Int: Int]()
4+
var i = 0
5+
for num in nums {
6+
map[num] = i
7+
i = i + 1
8+
}
9+
i = 0
10+
for num in nums {
11+
if let otherIndex = map[target - num], otherIndex != i {
12+
return [i, otherIndex]
13+
}
14+
i = i + 1
15+
}
16+
return []
17+
}
18+
}

0 commit comments

Comments
 (0)