1
- ### 34. Search for a Range
1
+ # 34. Find First and Last Position of Element in Sorted Array
2
2
3
+ ** <font color =red >难度: Medium</font >**
3
4
5
+ ## 刷题内容
4
6
5
- 题目:
7
+ > 原题连接
6
8
7
- https://leetcode.com/problems/search-for-a-range /
9
+ * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description /
8
10
11
+ > 内容描述
9
12
13
+ ```
14
+ Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
15
+
16
+ Your algorithm's runtime complexity must be in the order of O(log n).
17
+
18
+ If the target is not found in the array, return [-1, -1].
10
19
11
- 难度 : Medium
20
+ Example 1:
12
21
22
+ Input: nums = [5,7,7,8,8,10], target = 8
23
+ Output: [3,4]
24
+ Example 2:
25
+
26
+ Input: nums = [5,7,7,8,8,10], target = 6
27
+ Output: [-1,-1]
28
+ ```
13
29
30
+ ## 解题方案
14
31
15
- 思路:
32
+ > 思路 1
33
+ ****** - 时间复杂度: O(lgN)****** - 空间复杂度: O(1)******
16
34
17
35
二分法,先找``` target ``` 出现的左边界,判断是否有``` target ``` 后再判断右边界
18
36
30
48
31
49
AC 代码
32
50
33
-
34
-
35
-
36
51
``` python
37
52
class Solution (object ):
38
53
def searchRange (self , nums , target ):
@@ -41,7 +56,8 @@ class Solution(object):
41
56
:type target: int
42
57
:rtype: List[int]
43
58
"""
44
- if not nums : return [- 1 , - 1 ]
59
+ if not nums or len (nums) == 0 :
60
+ return [- 1 , - 1 ]
45
61
46
62
res = []
47
63
l, r = 0 , len (nums)- 1
@@ -57,6 +73,7 @@ class Solution(object):
57
73
r = mid - 1
58
74
if not res:
59
75
return [- 1 , - 1 ]
76
+
60
77
# search for right bound
61
78
r = len (nums)- 1
62
79
while l <= r:
0 commit comments