title: Given a sorted array, find out the scope of the given target value, the complexity of the algorithm is required in O (Logn), and if not found, returns [-1,-1];
Example:
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
Return [3, 4]
.
Problem Solving Ideas:
When we see the time complexity O (logn), we naturally want to use the two-point method, this problem, we naturally also use a two-point method;
Mid = (start + end)/2; There are three relationships between Target and Nums[mid]:
1) Target <nums[mid], then the latter part is discarded, end = mid-1;
2) Target > Nums[mid], the first half is discarded, start = mid + 1;
3) target = Nums[mid], this situation can not simply discard which half, but to go from the middle to the ends of the traversal, until the boundary is found;
The code is as follows:
1 Public classSolution {2 Public int[] Searchrange (int[] Nums,inttarget) {3 if(Nums = =NULL|| Nums.length < 1)4 return New int[]{-1,-1};5 int[] res =New int[2];6Res[0] = 1;7RES[1] = 1;8 intStart = 0;9 intEnd = Nums.length-1;Ten intMID = 0; One while(Start <=end) A { -Mid = (start + end)/2; - if(Nums[mid] <target) theStart = mid + 1; - Else if(Nums[mid] >target) -End = Mid-1; - Else + { -Start =mid; +End =mid; A while(Start >= 0 && Nums[start] = =target) atstart--; - while(End < Nums.length && Nums[end] = =target) -end++; - return New int[]{start + 1, end-1}; - } - } in returnRes; - } to}
Leetcode34--->search for a range (to find out what the given value appears in the sorted array)