Search in Rotated Sorted Array
Suppose a sorted array 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 are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
class Solution { public: int search(vector<int>& nums, int target) { if(nums.size() == 0) return -1; if(nums.size() == 1) if(nums[0] == target) return 0; int left = 0; int right = nums.size()-1; int mid = (right + left) / 2; int ans = -1; while(left < right) { mid = (right + left) / 2; if(nums[mid] == target) { return mid; } else if(right - left == 1) { if(nums[right] == target) ans = right; break; } else if(nums[mid] > nums[left]) { if(nums[mid] > target && nums[left] <= target) //[3,5,1], 1; output:-1; expected:2。nums[left] <= target条件忘了给,而且要给=号 right = mid; else left = mid; } else if(nums[mid] < nums[right]) { if(nums[mid] < target && nums[right] >= target) //nums[right] >= target条件忘了给,而且要给=号 left = mid; else right = mid; } } return ans; } };
//方法一:自测Accepted //observation is the key, try to solve it by modifying binary search class Solution { public: int search(int A[], int n, int target) { if( n==0 ) return -1; int mid = 0; int left=0, right=n-1; while( left <= right) { mid = left + (right-left)/2 ; if(A[mid] == target) return mid; if( A[left] <= A[mid] ) //left side sorted, including mid, it is sorted in [l,mid] { if( A[mid] > target && A[left] <= target ) right = mid - 1; else left = mid + 1; } else if ( A[mid] <= A[right] ) //right side sorted, [mid,r] must be sorted, if [l,mid] not sorted { if ( A[mid] < target && A[right] >= target ) left = mid + 1; else right = mid - 1; } } return -1; } };
//方法二:其他版本 class Solution { public: int search(int A[], int n, int target) { int left = 0; int right = n-1; while(left < right) { int mid = left+(right-left)/2; if(A[mid] >= A[left])//left side sorted, including mid, { if(A[left] <= target && target <= A[mid]) right = mid; else left = mid+1; } else//right side sorted { if(A[mid] <= target && target <= A[right]) left = mid; else right = mid-1; } } if(right >= 0 && right < n && A[right] == target) return right; else return -1; } };