Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int>fail; fail.push_back(-1); fail.push_back(-1); vector<int>ret; if(n<=0){ return fail; } if(n==1){ if(A[0]==target){ ret.push_back(0); ret.push_back(0); return ret; } else return fail; } int index1=-1,index2=n; //find the last element less than target int start,end; start=0;end=n-1; while(start<=end){ int mid=(start+end)/2; if(A[mid]>=target){ end=mid-1; } else{ if(mid==n-1){ index1=mid; break; } if(A[mid+1]>=target){ index1=mid; break; } else{ start=mid+1; } } } //find the first element great than target start=0;end=n-1; while(start<=end){ int mid=(start+end)/2; if(A[mid]<=target){ start=mid+1; } else{ if(mid==0){ index2=0; break; } else{ if(A[mid-1]<=target){ index2=mid; break; } else{ end=mid-1; } } } } if(index1==index2-1)return fail; else{ ret.push_back(index1+1); ret.push_back(index2-1); return ret; } } };