33. Search in Rotated Sorted Array
When execution: 4 ms, beat the 90.71% of all users to submit in C ++
Memory consumption: 9 MB, beat the 5.13% of all users to submit in C ++
From the ordered sequence can be seen, this problem binary search BinarySearch deformation , will temporarily sequence under the title search conditions referred to rotatedSearch, then the problem can be divided into:
1. When target is in the fully ordered (pivot point of rotation is not present in the sequence), performed at the binary search;
2. When the target in a non-fully ordered (with rotation pivot point sequence), performed at the rotation search (recursion);
All cases no more than two , the rotation point the first half or the second half of the following example:
1. [2, 3, 4, 5, 0, 1], for example, the point of rotation in the latter half, of the conditions determined mid (4)> first (2). Then when the value of the target in the [first, mid] between, target in the first half, on the first half for BinarySerach, otherwise described target in the latter half of the non-fully ordered sequence, then the second half after RotateSearch;
2. Similarly [5, 0, 1, 2, 3, 4], for example, half of the first rotation point, the condition is determined mid (1) <first (5), then when the value of the target is located [mid, end] when, in the latter half of the target, after half of the BinarySearch, completely or non-target sequences in the first half, a first half of RotateSerach;
The core algorithm was described above, the specific details, see the code:
class Solution {
private:
int binarySearch(vector<int>& nums, int s, int e, int target){
if(s > e){
return -1;
}
int lo = s, hi = e;
while(lo <= hi){
int mid = (lo + hi) / 2;
if(nums[mid] == target){
return mid;
}
else if(target < nums[mid]){
hi = mid - 1;
}
else{
lo = mid + 1;
}
}
return -1;
}
int rotatedSearch(vector<int>& nums, int s, int e, int target){
int fir = s, end = e;
if(fir > end){
return -1;
}
int mid = (fir + end) / 2;
if(mid == fir){
if(target == nums[mid]){
return mid;
}
else if(target == nums[end]){
return end;
}
return -1;
}
else if(nums[mid] > nums[fir]){
if(nums[fir] <= target && target <= nums[mid]){
return binarySearch(nums, fir, mid, target);
}
else{
return rotatedSearch(nums, mid+1, end, target);
}
}
else{
if(nums[mid] <= target && target <= nums[end]){
return binarySearch(nums, mid, end, target);
}
else{
return rotatedSearch(nums, fir, mid, target);
}
}
}
public:
int search(vector<int>& nums, int target) {
if(nums.size() == 0){
return -1;
}
else if(nums.size() == 1){
return (target == nums[0] ? 0 : -1);
}
return rotatedSearch(nums, 0, nums.size()-1, target);
}
};