搜索旋转有序数组

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if(nums.size()==0) return -1;

        int left=0,right=nums.size()-1;
        while(left+1<right){
            int mid=left+((right-left)>>1);

            if(nums[mid]==target) return mid;

            if(nums[mid]<nums[right]){
                if(nums[mid]<=target && target<=nums[right]){
                    left=mid;
                }
                else{
                    right=mid;
                }
            }
            else if(nums[mid]>nums[right]){
                if(nums[left]<=target && target<=nums[mid]){
                    right=mid;
                }
                else{
                    left=mid;
                }
            }
            else{
                right-=1;
            }
        }
        if(nums[left]==target) return left;
        else if(nums[right]==target) return right;
        else return -1;
    }
};

 

posted @ 2020-03-07 18:04  7aughing  阅读(130)  评论(0编辑  收藏  举报