Leetcode 33. Search in Rotated Sorted Array
You are given an integer array nums sorted in ascending order (with distinct values), and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You should search for target in nums and if you find it, return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
nums be empty?
-1.nums?
nums will contain distinct integers and will be rotated at some pivot.-1.We can utilize a modified binary search to achieve the O(log n) runtime complexity. The key insight is to determine which part of the array is normally ordered, and then decide whether the target lies within that range or in the other part.
low to 0 and high to nums.size() - 1.low <= high:
mid as the middle index of low and high.nums[mid] equals the target. If it does, return mid.nums[low] <= nums[mid], the left side is normally ordered:
nums[low] and nums[mid]. If it is, narrow the search to the left by setting high to mid - 1.low to mid + 1.nums[mid] and nums[high]. If it is, narrow the search to the right by setting low to mid + 1.high to mid - 1.-1.#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.empty()) return -1;
int low = 0;
int high = nums.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[low] <= nums[mid]) {
// Left side is normally ordered
if (nums[low] <= target && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
// Right side is normally ordered
if (nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
};
O(log n) time because each iteration of the while loop narrows the search range by half.O(1) since we are using a constant amount of extra space.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?