Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [], target = 0
Output: [-1,-1]
Solution: (Binary Search)
class Solution
{
public:
int firstOcc(vector<int> &arr, int start, int end, int target)
{
while (start <= end)
{
int mid = (start + end) / 2;
if ((mid == 0 || arr[mid - 1] < arr[mid]) && arr[mid] == target)
{
return mid;
}
else if (target <= arr[mid] )
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return -1;
}
int lastOcc(vector<int> &arr, int start, int end, int target)
{
while (start <= end)
{
int mid = (start + end) / 2;
if ((mid == arr.size() - 1 || arr[mid + 1] > arr[mid]) && arr[mid] == target)
{
return mid;
}
else if (target >= arr[mid])
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return -1;
}
vector<int> searchRange(vector<int> &nums, int target)
{
vector<int> v;
int start = firstOcc(nums, 0, nums.size() - 1, target);
int end = lastOcc(nums, 0, nums.size() - 1, target);
v.push_back(start);
v.push_back(end);
return v;
}
};