Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
I wrote this code in leetcode but it has only passed 67 test cases out of 88.Can someone please tell me the problem with this code.
class Solution {
public:
int FirstOccurence(vector<int> arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
// maybe an answer
if (arr[mid] == x) {
ans=mid;
high=mid-1;
}
else if (arr[mid]< x) {
low=mid+1;
}
else high=mid-1;
}
return ans;
}
int LastOccurence(vector<int> arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
// maybe an answer
if (arr[mid]== x) {
ans = mid;
//look for smaller index on the left
low=mid+1;
}
else if(arr[mid]>x){
high=mid-1;
}
else {
low = mid + 1; // look on the right
}
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size()-1;
int k=target;
int a=FirstOccurence(nums,n,k);
int b=LastOccurence(nums,n,k);
return{a,b};
}
};