@@ -17,22 +17,34 @@ class Solution:
1717 # @param target, an integer to be searched
1818 # @return a list of length 2, [index1, index2]
1919 def searchRange (self , A , target ):
20- left = self .binarySearch (lambda x , y : x > y , A , target )
20+ # Find the first index where target <= A[idx]
21+ left = self .binarySearch (lambda x , y : x <= y , A , target )
2122 if left >= len (A ) or A [left ] != target :
2223 return [- 1 , - 1 ]
23- right = self .binarySearch (lambda x , y : x >= y , A , target )
24+ # Find the first index where target < A[idx]
25+ right = self .binarySearch (lambda x , y : x < y , A , target )
2426 return [left , right - 1 ]
2527
2628 def binarySearch (self , compare , A , target ):
2729 start , end = 0 , len (A )
2830 while start < end :
2931 mid = start + (end - start ) / 2
3032 if compare (target , A [mid ]):
33+ end = mid
34+ else :
3135 start = mid + 1
36+ return start
37+
38+ def binarySearch2 (self , compare , A , target ):
39+ start , end = 0 , len (A ) - 1
40+ while start <= end :
41+ mid = start + (end - start ) / 2
42+ if compare (target , A [mid ]):
43+ end = mid - 1
3244 else :
33- end = mid
45+ start = mid + 1
3446 return start
3547
3648if __name__ == "__main__" :
3749 print Solution ().searchRange ([2 , 2 ], 3 )
38- print Solution ().searchRange ([5 , 7 , 7 , 8 , 8 , 10 ], 8 )
50+ print Solution ().searchRange ([5 , 7 , 7 , 8 , 8 , 10 ], 8 )
0 commit comments