Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc43779

Browse files
Update 035._search_insert_position.md
1 parent b5d01b8 commit fc43779

File tree

1 file changed

+44
-13
lines changed

1 file changed

+44
-13
lines changed
Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,45 @@
1-
### 35. Search Insert Position
1+
# 35. Search Insert Position
22

3-
题目:
4-
<https://leetcode.com/problems/search-insert-position/>
3+
**<font color=red>难度: Easy</font>**
54

5+
## 刷题内容
66

7-
难度:
7+
> 原题连接
88
9-
Medium
9+
* https://leetcode.com/problems/search-insert-position/description/
10+
11+
> 内容描述
12+
13+
```
14+
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
15+
16+
You may assume no duplicates in the array.
17+
18+
Example 1:
19+
20+
Input: [1,3,5,6], 5
21+
Output: 2
22+
Example 2:
23+
24+
Input: [1,3,5,6], 2
25+
Output: 1
26+
Example 3:
27+
28+
Input: [1,3,5,6], 7
29+
Output: 4
30+
Example 4:
31+
32+
Input: [1,3,5,6], 0
33+
Output: 0
34+
```
35+
36+
## 解题方案
37+
38+
> 思路 1
39+
******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)******
1040

1141
找到第一个比```target```大的值的```index```,如果没找到则返回```len(nums)```,但是代码中直接返回```i```值就行了
1242

13-
### 思路一:暴力
1443

1544
```python
1645
class Solution(object):
@@ -27,7 +56,9 @@ class Solution(object):
2756
return i
2857
return i
2958
```
30-
### 思路二:二分
59+
60+
> 思路 2
61+
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(1)******
3162

3263
```python
3364
class Solution(object):
@@ -37,12 +68,12 @@ class Solution(object):
3768
:type target: int
3869
:rtype: int
3970
"""
40-
left, right = 0, len(nums) - 1
41-
while left <= right:
42-
mid = left + ((right - left) >> 2)
71+
l, r = 0, len(nums) - 1
72+
while l <= r:
73+
mid = l + ((r-l) >> 2)
4374
if nums[mid] < target:
44-
left = mid + 1
75+
l = mid + 1
4576
else:
46-
right = mid - 1
47-
return left
77+
r = mid - 1
78+
return l
4879
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /