首页 > 代码库 > Search in Rotated Sorted Array I && II

Search in Rotated Sorted Array I && II

对翻过一次的排序数组二分查找,要利用好已排序这个条件

class Solution {
public:
    int search(int A[], int n, int target) {
        int left = 0, right = n-1;
        while(left <= right){
             int mid = (left+right)/2;
             if(A[mid] == target)
               return mid;
             if(A[left] <= A[mid]){
              if(A[left] <= target && target < A[mid])
                right = mid-1;
              else 
                left = mid+1;
             }
             else {
              if(A[mid] < target && target <= A[right])
                left = mid+1;
              else 
                right = mid-1;
             }
        }
        return -1;
    }
};

II中允许重复数字,碰到相等的向前移。

class Solution {
public:
    bool search(int A[], int n, int target) {
        int left = 0, right = n-1;
        while(left <= right){
             int mid = (left+right)/2;
             if(A[mid] == target)
               return true;
             if(A[left] < A[mid]){
              if(A[left] <= target && target < A[mid])
                right = mid-1;
              else 
                left = mid+1;
             }
             else if(A[left] > A[mid]){
              if(A[mid] < target && target <= A[right])
                left = mid+1;
              else 
                right = mid-1;
             }
             else left++;
        }
        return false;
    }
};


Search in Rotated Sorted Array I && II