添加0035.搜索插入位置 Swift版本

This commit is contained in:
YDLIN
2021-08-06 10:56:21 +08:00
parent f351b222a5
commit 18bf14707c
2 changed files with 36 additions and 5 deletions

BIN
pics/.DS_Store vendored

Binary file not shown.

View File

@ -234,8 +234,6 @@ class Solution {
``` ```
Python Python
```python3 ```python3
class Solution: class Solution:
@ -254,9 +252,6 @@ class Solution:
return right + 1 return right + 1
``` ```
Go
JavaScript: JavaScript:
```js ```js
var searchInsert = function (nums, target) { var searchInsert = function (nums, target) {
@ -277,6 +272,42 @@ var searchInsert = function (nums, target) {
}; };
``` ```
Swift:
```swift
// 暴力法
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
for i in 0..<nums.count {
if nums[i] >= target {
return i
}
}
return nums.count
}
// 二分法
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var left = 0
var right = nums.count - 1
while left <= right {
let middle = left + ((right - left) >> 1)
if nums[middle] > target {
right = middle - 1
}else if nums[middle] < target {
left = middle + 1
}else if nums[middle] == target {
return middle
}
}
return right + 1
}
```
----------------------- -----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)