@@ -78,7 +78,7 @@ class Solution:
7878class Solution :
7979 def search (self , nums : List[int ], target : int ) -> int :
8080
81- l, r = 0 , len (nums)
81+ l, r = 0 , len (nums) - 1
8282
8383 while l < r:
8484 mid = (l + r) // 2
@@ -87,7 +87,7 @@ class Solution:
8787 else :
8888 r = mid
8989
90- if l < len (nums) and nums[l] == target:
90+ if nums[l] == target:
9191 return l
9292
9393 return - 1
@@ -97,14 +97,14 @@ class Solution:
9797
9898## 常见题目
9999
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/ )
101101
102- > 给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
103- > 如果目标值不在数组中,则返回` [-1, -1] `
102+ > 给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。如果目标值不在数组中,则返回` [-1, -1] `
104103
105104思路:核心点就是找第一个 target 的索引,和最后一个 target 的索引,所以用两次二分搜索分别找第一次和最后一次的位置
106105
107106``` Python
107+ # 使用模板3的解法
108108class Solution :
109109 def searchRange (self , nums , target ):
110110 Range = [- 1 , - 1 ]
@@ -123,6 +123,8 @@ class Solution:
123123 Range[0 ] = l
124124 elif nums[r] == target:
125125 Range[0 ] = r
126+ else :
127+ return Range
126128
127129 l, r = 0 , len (nums) - 1
128130 while l + 1 < r:
@@ -134,12 +136,47 @@ class Solution:
134136
135137 if nums[r] == target:
136138 Range[1 ] = r
137- elif nums[l] == target :
139+ else :
138140 Range[1 ] = l
139141
140142 return Range
141143```
142144
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+
143180### [ search-insert-position] ( https://leetcode-cn.com/problems/search-insert-position/ )
144181
145182> 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
0 commit comments