int firstOccurance(vector<int> &ar,int target){
int low = 0,high = ar.size()-1,ans = -1;
while(low<=high){
int mid = low+(high-low)/2;
if(ar[mid]==target){
//mid can be our answer but we are not sure so reduce the search space
ans = mid;
high = mid-1;//for first occurance go to left
}
else if(ar[mid]>target)
high = mid-1;
else
low = mid+1;
}
return ans;//if element is not present ans will remain -1,and will be returned as it is.
}
int lastOccurance(vector<int> &ar,int target){
int low = 0,high = ar.size()-1,ans = -1;
while(low<=high){
int mid = low+(high-low)/2;
if(ar[mid]==target){
//mid can be our answer but we are not sure so reduce the search space
ans = mid;
low = mid+1; //for lasat occurance go to right
}
else if(ar[mid]>target)
high = mid-1;
else
low = mid+1;
}
return ans;//if element is not present ans will remain -1,and will be returned as it is.
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter