title :
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O(log n).
If the target is not a found in the array, return [-1, -1] .
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
Return [3, 4] .
code : OJ Test via runtime:91 ms
1 classSolution:2 #@param A, a list of integers3 #@param target, an integer to be searched4 #@return A list of length 2, [Index1, Index2]5 defSearchalltarget (self, A, index, target):6 #Left index7Left_index =Index8Curr_index =Index9 whileCurr_index>=0 anda[curr_index]==Target:TenLeft_index =Curr_index OneCurr_index = curr_index-1 A #Right index -Right_index =Index -Curr_index =Index the whileCurr_index<len (A) anda[curr_index]==Target: -Right_index =Curr_index -Curr_index = curr_index+1 - return[Left_index,right_index] + - defSearchrange (self, A, target): + #None case A ifA isNone: at returnNone - #Short Length Cases - ifLen (A) ==1 : - return[[ -1,-1],[0,0]] [a[0]==Target] - #binary Search -Start =0 inend = Len (A)-1 - whilestart<=End: to ifstart==End: + ifa[start]==Target: - returnSelf.searchalltarget (A, start, target) the Else : * return[ -1,-1] $ ifstart+1==End:Panax Notoginseng ifa[start]==Target: - returnSelf.searchalltarget (A, start, target) the elifa[end]==Target: + returnSelf.searchalltarget (A, end, target) A Else : the return[ -1,-1] +Mid = (start+end)/2 - ifa[mid]==Target: $ returnSelf.searchalltarget (A, Mid, target) $ elifA[mid]>Target: -End = Mid-1 - Else : theStart = Mid+1
Ideas :
This problem is still based on binary search, but the requirement to find a range of values.
Complete in two steps:
Step1. Regular binary finds an index of target, or returns [ -1,-1] if not found
Step2. Assuming that there may be more than one position of target in a, the index found from Step1 begins to search left and right until the target on both sides of index is found.
Job
Leetcode "Search for a Range" Python implementation