Search for a Range
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] .
Problem Solving Ideas:
The test instructions of this problem is to find the subscript range of the target values in the sorted array, which may have the same elements.
The topic requires time complexity in O (Logn). 3-time binary search. For the first time, we find a subscript k with a value of target, a second time to find the smallest subscript with a value of target in 0~k, and the third to find the largest subscript in the k~len-1 with a value of target. The time complexity is O (Logn) per time.
Class Solution {public:vector<int> Searchrange (vector<int>& nums, int target) {VECTOR<INT&G T Result ({-1,-1}); int start=0, End=nums.size ()-1; int middle; Find the first while (Start<=end) {middle= (start+end)/2; if (nums[middle]==target) {result[0]=result[1]=middle; Break }else if (nums[middle]>target) {end=middle-1; }else{start=middle+1; }} if (Result[0]!=-1) {//Find the smallest subscript start=0; End=result[0]-1; while (start<=end) {middle= (start+end)/2; if (nums[middle]==target) {end=middle-1; Result[0]=middle; }else{start=middle+1; }}//Find the largest subscript start=result[1]+1; End=nums.size ()-1;while (start<=end) {middle= (start+end)/2; if (nums[middle]==target) {start=middle+1; Result[1]=middle; }else{end=middle-1; }}} return result; }};
[Leetcode] Search for a Range