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] .
Ideas
Search by binary, if not found return [ -1,-1] If you find middle, find start and ending.
1 Public classSolution {2 Public int[] Searchrange (int[] A,inttarget) {3 BooleanFound =false;4 intLow = 0;5 intHigh = A.length-1;6 intMiddle = 0;7 intResult[] =New int[2];8 9 while(Low <=High ) {TenMiddle = (low + high)/2; One if(Target >A[middle]) { ALow = middle + 1; - } - Else if(Target <A[middle]) { theHigh = Middle-1; - } - Else - { +Found =true; - Break; + } A}// while at if(!found)//did not find the - { -Result[0] = 1; -RESULT[1] = 1; -}//if - Else{ in while(Middle >= 0 && a[middle] = =target) { -middle--; to } + if(Middle < 0) -Result[0] = 0; the Else *Result[0] = middle + 1; $Middle = result[0];Panax Notoginseng while(Middle < a.length && A[middle] = =target) { -middle++; the } + if(Middle >=a.length) ARESULT[1] = a.length-1; the Else +RESULT[1] = middle-1; -}//Else $ returnresult; $ } -}
Search for a Range