class Solution {
//Binary Search
//we must know how to process the 3 cases below:
//1.how to find the right most target
//2.how to find the left most target
//3.how to find the insert position
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int l = 0;
int r = n-1;
while (l <= r)
{
int mid = l+(r-l)/2;
if (A[mid] >= target)//find the left most target
r = mid-1;
else if (A[mid] < target)
l = mid+1;
}
int left = l;
l = 0;
r = n-1;
while (l <= r)
{
int mid = l+(r-l)/2;
if (A[mid] > target)//find the right most target
r = mid-1;
else if (A[mid] <= target)
l = mid+1;
}
int right = r;
if(A[left] != target || A[right] != target)
left = right = -1;
vector<int> ans(2);
ans[0] = left;
ans[1] = right;
return ans;
}
};
second time
class Solution {
public:
int findLeftMost(int A[], int n, int target)
{
if(n == 0) return -1;
int left = 0;
int right = n-1;
while(left < right)
{
int mid = left+(right-left)/2;
if(A[mid] >= target) right = mid;
else left = mid+1;
}
if(A[left] == target) return left;
else return -1;
}
int findRightMost(int A[], int n, int target)
{
if(n == 0) return -1;
int left = 0;
int right = n-1;
while(left <= right)
{
int mid = left+(right-left)/2;
if(A[mid] > target) right = mid-1;
else left = mid+1;
}
if(A[right] == target) return right;
else return -1;
}
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int startPos = findLeftMost(A, n, target);
int endPos = findRightMost(A, n, target);
vector<int> ans(2);
ans[0] = startPos; ans[1] = endPos;
return ans;
}
};