@@ -78,7 +78,7 @@ class Solution:
78
78
class Solution :
79
79
def search (self ,nums : List[int ],target :int ) ->int :
80
80
81
- l, r= 0 ,len (nums)
81
+ l, r= 0 ,len (nums)- 1
82
82
83
83
while l< r:
84
84
mid= (l+ r)// 2
@@ -87,7 +87,7 @@ class Solution:
87
87
else :
88
88
r= mid
89
89
90
- if l < len (nums) and nums[l]== target:
90
+ if nums[l]== target:
91
91
return l
92
92
93
93
return - 1
@@ -97,14 +97,14 @@ class Solution:
97
97
98
98
##常见题目
99
99
100
- ###[ search-for-range ] ( https://www.lintcode. com/problem/search-for-a-range/description )
100
+ ###[ find-first-and-last-position-of-element-in-sorted-array ] ( https://leetcode-cn. com/problems/find-first-and-last-position-of-element-in-sorted-array/ )
101
101
102
- > 给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
103
- > 如果目标值不在数组中,则返回` [-1, -1] `
102
+ > 给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。如果目标值不在数组中,则返回` [-1, -1] `
104
103
105
104
思路:核心点就是找第一个 target 的索引,和最后一个 target 的索引,所以用两次二分搜索分别找第一次和最后一次的位置
106
105
107
106
``` Python
107
+ # 使用模板3的解法
108
108
class Solution :
109
109
def searchRange (self ,nums ,target ):
110
110
Range= [- 1 ,- 1 ]
@@ -123,6 +123,8 @@ class Solution:
123
123
Range[0 ]= l
124
124
elif nums[r]== target:
125
125
Range[0 ]= r
126
+ else :
127
+ return Range
126
128
127
129
l, r= 0 ,len (nums)- 1
128
130
while l+ 1 < r:
@@ -134,12 +136,47 @@ class Solution:
134
136
135
137
if nums[r]== target:
136
138
Range[1 ]= r
137
- elif nums[l] == target :
139
+ else :
138
140
Range[1 ]= l
139
141
140
142
return Range
141
143
```
142
144
145
+ ``` Python
146
+ # 使用模板2的解法
147
+ class Solution :
148
+ def searchRange (self ,nums ,target ):
149
+ Range= [- 1 ,- 1 ]
150
+ if len (nums)== 0 :
151
+ return Range
152
+
153
+ l, r= 0 ,len (nums)- 1
154
+ while l< r:
155
+ mid= (l+ r)// 2
156
+ if nums[mid]< target:
157
+ l= mid+ 1
158
+ else :
159
+ r= mid
160
+
161
+ if nums[l]== target:
162
+ Range[0 ]= l
163
+ else :
164
+ return Range
165
+
166
+ l, r= 0 ,len (nums)- 1
167
+ while l< r:
168
+ mid= (l+ r+ 1 )// 2
169
+ if nums[mid]> target:
170
+ r= mid- 1
171
+ else :
172
+ l= mid
173
+
174
+ Range[1 ]= l
175
+ return Range
176
+ ```
177
+
178
+
179
+
143
180
###[ search-insert-position] ( https://leetcode-cn.com/problems/search-insert-position/ )
144
181
145
182
> 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。