Leetcode: Search in Rotated Sorted Array

来源:互联网 发布:毛概网络课程答案 编辑:程序博客网 时间:2024/05/18 20:51

http://oj.leetcode.com/problems/search-in-rotated-sorted-array/


class Solution {public:    // The key idea is that the start value and end value    // can limite possible values of the array in a range, even though they may be rotated.    // So we still can use binary search    bool IsItPossible(int start, int end, int target){        if(start==target||end==target) return true;        if(start<end) return target>start&&target<end;        else if(start>end) return target>start||target<end;        else return false;    }    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(IsItPossible(A[0],A[mid],target)) right=mid-1;            else left=mid+1;        }        return -1;    }};


原创粉丝点击