有人用了很复杂的讨论-,-
我感觉我是考虑不了那么多。。
那么我先二分找到那个分割点,然后。。。分两段来二分找
class Solution { public: int bs(int A[] , int start , int end , int target){ int l = start; int r = end; while(l <= r){ int mid = (l + r) / 2; if(A[mid] == target) return mid; if(A[mid] < target) l = mid + 1; else r = mid - 1; } return -1; } int search(int A[], int n, int target) { if(n <= 0) return -1; int l = 0; int r = n - 1; while(l < r) { int mid = (l + r) / 2; if(A[mid] > A[l]) l = mid; else r = mid; } //split l int idx = bs(A , 0 , l , target); if(idx != -1) return idx; return bs(A , l + 1 , n-1, target); } };
------update 07/20/2014----
我也讨论下,其实就几种情况
mid,target在左边还是右边的区域,然后该怎么做。
class Solution { public: int search(int A[], int n, int target) { int l = 0; int r = n - 1; while(l <= r) { int mid = (r-l)/2+l; if (A[mid] == target) return mid; if (A[mid] >= A[l]) { //left if (target < A[l]) { //target is on the right l = mid + 1; } else { //target is on the left if (A[mid] < target) { l = mid + 1; } else { r = mid - 1; } } } else { //right if (target <= A[r]) { //target is on the right if (A[mid] < target) { l = mid + 1; } else { r = mid - 1; } } else { r = mid - 1; } } } return -1; } };
by 1957