File tree 2 files changed +53
-0
lines changed
lcof/面试题53 - I. 在排序数组中查找数字 I
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -193,6 +193,35 @@ public class Solution {
193
193
}
194
194
```
195
195
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
+
196
225
<!-- tabs: end -->
197
226
198
227
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments