forked from algorhythms/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
032 Search for a Range.py
53 lines (44 loc) · 1.44 KB
/
032 Search for a Range.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
"""
__author__ = 'Danyang'
class Solution:
def searchRange(self, A, target):
"""
Binary Search Twice
Notice the low-bound & high-bound binary search
:param A: a list of integers
:param target: an integer to be searched
:return: a list of length 2, [index1, index2]
"""
result = []
length = len(A)
# low-bound binary search
start = 0
end = length # [0, length)
while start<end:
mid = (start+end)/2
if A[mid]<target: # NOTICE: less than
start = mid+1
else:
end = mid
if start<length and A[start]==target:
result.append(start)
else:
return [-1, -1]
# high-bound binary search
start = start
end = length # no "-1" # [0, length)
while start<end:
mid = (start+end)/2
if A[mid]<=target: # NOTICE: less than or equal
start = mid+1
else:
end = mid
result.append(start-1)
return result