Q: 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 and [5, 7, 7, 8, 8, 10] target value 8, return [3, 4] .
Analysis: because there are sequential sequences, it should be possible to find by means of dichotomy. Two recursive exits: (1) n=1 and no targets found; (2) The target has been found.
Note the case of TARGET>A[N/2], when the [A+N/2, N-N/2] sub-sequence is re-recursive lookup, the return value of the target position to add the previous N/2.
Class Solution {public: vector<int> searchrange (int a[], int n, int target) { vector<int> ret; if (n = = 1 && target!=a[0]) //Recursive exit 1, the target value ret.assign (2,-1) is not found; else if (target = = A[n/2]) { //Recursive exit 2, locate the target value int Tbeg = N/2, tend = N/2; while ((--tbeg) >= 0 && target = = A[tbeg]); while ((++tend) < n && target = = A[tend]); Ret.push_back (Tbeg + 1); Ret.push_back (tend-1); } else if (target < A[N/2]) ret = Searchrange (A, N/2, target); else{ ret = searchrange (A + N/2, N-N/2, target); if (ret[0] = =-1 && ret[1] = = 1) return ret; Ret[0] + = N/2; RET[1] + = N/2; attention*** } return ret;} ;
Leetcode--Search for a Range