The problem:
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] .
My Analysis:
The idea behind this question is very elegant and tricky.
Key:when the target value is found, we were not return it (very important). We keep going to reach the the boundry.
It's very skllful to write the right checking condition, and read the "right" value from the proper pointer.
1. When we reach the "the left" most target, we stop the "low pointer" (left pointer).
if (A[mid] < target)//we move the low pointer only then A[mid] is strictly smaller than target.
Low = mid + 1;
else//a[mid] <= target, we keep move high Pinter, even when a[mid] = = target.
High = Mid-1
2. The same idea could is used to find the right most target, we stop the high pointer (right pointer).
if (A[mid] <= target)
Low = mid + 1;
else//a[mid] > target, we move high pointer only if A[MID] is strictly larger than target.
High = mid-1;
My Solution:
Public classSolution { Public int[] Searchrange (int[] A,inttarget) { int[] ret =New int[2]; ret[0] = 1; ret[1] = 1; if(A.length = = 0) returnret; intLlow = 0; intLhigh = a.length-1; intRlow = 0; intRhigh = a.length-1; intMID =-1; while(Llow <=Lhigh) {Mid= (llow + lhigh)/2; if(A[mid] < target)//The idea behind this approaching is very tricky and elegant!Llow = mid + 1; ElseLhigh= Mid-1; } while(Rlow <=Rhigh) {Mid= (Rlow + rhigh)/2; if(A[mid] <=target) Rlow= Mid + 1; ElseRhigh= Mid-1; } if(Llow <=Rhigh) {ret[0] =llow; ret[1] =Rhigh; } returnret; }}
[Leetcode#34] Search for a Range