Skip to content

Commit dca9e5e

Browse files
klever34yanglbme
andauthored
feat: add swift implementation to lcof2 problem: No.006 (doocs#2976)
* Swift implementation for LCOF2 006 * Update README.md * Update Solution.swift --------- Co-authored-by: Libin YANG <contact@yanglibin.info>
1 parent 4cca69a commit dca9e5e

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof2/剑指 Offer II 006. 排序数组中两个数字之和/README.md

+27
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,33 @@ impl Solution {
191191
}
192192
```
193193

194+
#### Swift
195+
196+
```swift
197+
class Solution {
198+
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
199+
let n = numbers.count
200+
for i in 0..<n {
201+
let x = target - numbers[i]
202+
var l = i + 1
203+
var r = n - 1
204+
while l < r {
205+
let mid = (l + r) / 2
206+
if numbers[mid] >= x {
207+
r = mid
208+
} else {
209+
l = mid + 1
210+
}
211+
}
212+
if l < n && numbers[l] == x {
213+
return [i, l]
214+
}
215+
}
216+
return []
217+
}
218+
}
219+
```
220+
194221
<!-- tabs:end -->
195222

196223
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
3+
let n = numbers.count
4+
for i in 0..<n {
5+
let x = target - numbers[i]
6+
var l = i + 1
7+
var r = n - 1
8+
while l < r {
9+
let mid = (l + r) / 2
10+
if numbers[mid] >= x {
11+
r = mid
12+
} else {
13+
l = mid + 1
14+
}
15+
}
16+
if l < n && numbers[l] == x {
17+
return [i, l]
18+
}
19+
}
20+
return []
21+
}
22+
}

0 commit comments

Comments
 (0)