Skip to content

Commit 0fdbff2

Browse files
authored
feat: add swift implementation to lcof problem: No.53 (#2938)
1 parent b600a76 commit 0fdbff2

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

lcof/面试题53 - I. 在排序数组中查找数字 I/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,35 @@ public class Solution {
193193
}
194194
```
195195

196+
#### Swift
197+
198+
```swift
199+
class Solution {
200+
private var nums: [Int] = []
201+
202+
func search(_ nums: [Int], _ target: Int) -> Int {
203+
self.nums = nums
204+
let leftIndex = search(target)
205+
let rightIndex = search(target + 1)
206+
return rightIndex - leftIndex
207+
}
208+
209+
private func search(_ x: Int) -> Int {
210+
var left = 0
211+
var right = nums.count
212+
while left < right {
213+
let mid = (left + right) / 2
214+
if nums[mid] >= x {
215+
right = mid
216+
} else {
217+
left = mid + 1
218+
}
219+
}
220+
return left
221+
}
222+
}
223+
```
224+
196225
<!-- tabs:end -->
197226

198227
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
private var nums: [Int] = []
3+
4+
func search(_ nums: [Int], _ target: Int) -> Int {
5+
self.nums = nums
6+
let leftIndex = search(target)
7+
let rightIndex = search(target + 1)
8+
return rightIndex - leftIndex
9+
}
10+
11+
private func search(_ x: Int) -> Int {
12+
var left = 0
13+
var right = nums.count
14+
while left < right {
15+
let mid = (left + right) / 2
16+
if nums[mid] >= x {
17+
right = mid
18+
} else {
19+
left = mid + 1
20+
}
21+
}
22+
return left
23+
}
24+
}

0 commit comments

Comments
 (0)