leetcode[34]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 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: int find(int A[],int n, int target, int Left, int Right, int flag) { if (A==NULL||n==0||Left>Right)return -1; int mid=(Left+Right)/2; if (A[mid]==target) { int pos=flag?find(A,n,target,Left,mid-1,flag):find(A,n,target,mid+1,Right,flag); if(pos==-1) return mid; else return pos; } else if (A[mid]>target) { find(A,n,target,Left,mid-1,flag); } else { find(A,n,target,mid+1,Right,flag); } } vector<int> searchRange(int A[], int n, int target) { vector<int> res; int lef=find(A,n,target,0,n-1,1); int rig=find(A,n,target,0,n-1,0); res.push_back(lef); res.push_back(rig); return res; } };