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.
找到左右分界点,然后判断target是在前半段还是后半段,然后在相应的地方用二分法查找
class Solution { public: bool binaryS(int A[], int min, int max, int &result, int target) { if(A[min] > target || A[max] <target) { result = -1 ; return false ; } int mid; while(min <= max) { mid = min + (max-min) /2 ; if(A[mid] == target) { result = mid; return true; } if(A[mid] < target) min = mid + 1; else max = mid -1; } result = -1; return false; } int search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function int i,result;
if(n < 2) { for(i = 0; i<n ; i++) if(A[i] == target) break; return i<n ? i: -1; } int min = 0,max = n-1 ,mid; while(min <= max) { mid = min + (max - min)/2 ; if(mid == 0 || mid == n-1) break; if(A[mid]<A[mid-1] && A[mid] <A[mid+1] ) break; else if(A[mid] <A[0]) max = mid ; else if(A[mid] >A[0]) min = mid + 1 ; } if(mid == 0) { if(A[0] > A[1]) mid = 1; else mid = -1 ; } if(mid == n-1) { if(A[n-1] >A[n-2]) mid = n ; } if( mid == -1 || mid == n ) binaryS(A, 0,n - 1, result, target) ; else if(target >= A[0]) binaryS(A, 0, mid - 1, result, target) ; else binaryS(A, mid, n-1, result, target); return result ; } };
另外一种思路:
class Solution { public: int search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function if(A == NULL || n < 0) return -1; int left = 0; int right = n-1; while(left <= right){ int mid = ((right - left)>>1) + left ; if(A[mid] == target) return mid; if(A[mid] > A[right]){ if(target >= A[left] && target < A[mid]) right = mid - 1; else left = mid + 1; }else{ if(target <= A[right] && target > A[mid]) left = mid + 1; else right = mid - 1; } } return -1; } };
另一种思路:
class Solution { public: int search(int A[], int n, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function if(A == NULL || n < 0) return -1; int left = 0; int right = n-1; while(left <= right){ int mid = ((right - left)>>1) + left ; if(A[mid] == target) return mid; if(A[mid] > A[left]){ if(target >= A[left] && target < A[mid]) right = mid - 1; else left = mid + 1; }else if(A[mid] < A[left]){ if(target <= A[right] && target > A[mid]) left = mid + 1; else right = mid - 1; }else{ if(target == A[left]) return left; ++left; } } return -1; } };