Describe:
Given an array of integers nums
sorted in ascending order, 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]
.
Example 1:
Input:nums = [ 5,7,7,8,8,10]
, target = 8Output: [3,4]
Example 2:
Input:nums = [ 5,7,7,8,8,10]
, target = 6Output: [ -1,-1]
Idea one: a binary Search
The first two points are used to find and taget the elements that are equal to the starting position, and then spread to both sides to find the same range of values.
classSolution { Public: Vector<int> Searchrange (vector<int>& Nums,inttarget) {Vector<int> Res (2,-1); if(nums.size () = =0)returnRes; intCau =dichotomy (nums,target); if(Cau = =-1)returnRes; Else{ inti = Cau,j =Cau; cout<<cau<<Endl; while((i>=0&& Nums[i] = = target) | | (J<=nums.size ()-1&& Nums[j] = =target)) { if(i>=0&& Nums[i] = =target) {res[0] =i; cout<<i<<Endl; I--; } if(J<=nums.size ()-1&& Nums[j] = =target) {res[1] =J; cout<<j<<Endl; J++; } } } returnRes; } intDichotomy (vector<int>& Nums,inttarget) { intLow =0,intHigh = Nums.size ()-1; while(Low <High ) { intMid = (Low + high +1) /2; if(Nums[mid] = = target)returnmid; if(Nums[mid] < target) Low = mid +1; ElseHigh = mid-1; } return-1; }};
Idea two: 23 times binary Search
First, based on the above two-point lookup, find the starting position of the element, and then start from low to continue using a binary search to find the location of the target+1, and then return to this position it-1, so as to find the start and end of the range.
classSolution { Public: Vector<int> Searchrange (vector<int>& Nums,inttarget) {Vector<int> Res (2,-1); if(nums.size () = =0)returnRes; intLow = dichotomy (Nums,target,0);//find the starting elementcout<<low<<Endl; if(Low = = Nums.size () | | nums[low]! = target)//may appear at the end of the array or target is larger than the element at low, low=nums.size returnRes; Else{res[0] =Low ; res[1] = dichotomy (nums,target+1, low)-1;//Find the end element } returnRes; } intDichotomy (vector<int>& Nums,intTargetintLow ) { intHigh = Nums.size ();//Core while(Low <High ) { intMid = (low + high)/2; if(Nums[mid] < target) Low = mid +1; ElseHigh =mid; } returnLow ; }};
"Leetcode" "find Element" find first and last Position of element in Sorted Array