Tuesday, August 8th
Value in a pivoted array
Given a sorted array without duplicates that may have been rotated, determine if the array contains a target value
int n = nums.size();
int l = 0, r = n - 1;
int mid;
while (l <= r) {
mid = (l + r) / 2;
if (nums[mid] > nums[n - 1]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
Then perform binary search over the two arrays split by the pivot. Binary search will be performed twice on the arrays, so we define a separate binary search function to call
int binarySearch(vector<int> nums, int l, int r, int target) {
int mid;
while (l <= r) {
mid = (l+r) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
The binary search function will be called twice, once for the array [0, left of pivot] and [pivot, end of array]. If the first call returns -1, then the target isn't in the first array.
int ans = binarySearch(nums, 0, l - 1, target);
if (ans != -1) return ans;
return binarySearch(nums, l, n - 1, target);
Solved 195/197 test cases with some devolved spaghetti code.
Thank you to the Editorial for firming up binary search
Comments
Post a Comment