int findJustSmaller(const vector<int>& arr, int target) {
int low = 0;
int high = arr.size() - 1;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
// If the current element is smaller than or equal to the target,
// we update the result and continue searching in the right half.
if (arr[mid] <= target) {
result = arr[mid];
low = mid + 1;
}
// If the current element is greater than the target, we search in the left half.
else {
high = mid - 1;
}
}
return result;
}
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