LintCode Q61 Search for a Range in Python

  • Jinhai ZHOU
  • 5 Minutes
  • 2016年12月24日
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
class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : a list of length 2, [index1, index2]
"""
def searchRange(self, A, target):
# write your code here
# time complexity: O(log(n))
# space complexity: O(1)
# use 2 binary research
if len(A) == 0:
return [-1, -1]
lo, hi = 0, len(A) - 1
while lo + 1 < hi:
mid = lo + (hi - lo)/2
if A[mid] < target:
lo = mid
else:
hi = mid
# current lo < hi
if A[lo] == target:
left_boundary = lo
elif A[hi] == target:
left_boundary = hi
else:
return [-1, -1]
lo, hi = 0, len(A) - 1
while lo + 1 < hi:
mid = lo + (hi - lo)/2
if A[mid] > target:
hi = mid
else:
lo = mid
# current lo < hi
if A[hi] == target:
right_boundary = hi
elif A[lo] == target:
right_boundary = lo
else:
return [-1, -1]
return [left_boundary, right_boundary]
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。