mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加0035.搜索插入位置 Swift版本
This commit is contained in:
BIN
pics/.DS_Store
vendored
BIN
pics/.DS_Store
vendored
Binary file not shown.
@ -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)
|
||||||
|
Reference in New Issue
Block a user