33. 搜索旋转排序数组

33. 搜索旋转排序数组


题目链接:33. 搜索旋转排序数组

代码如下:

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

        while(left<=right)
        {
            int mid=left+(right-left)/2;
            //int mid=(left+right)>>1;

            if(nums[mid]==target)
                return mid;
            else if(nums[mid]<nums[right])
            {
                if(nums[mid]<target&&target<=nums[right])//右边是有序的
                    left=mid+1;
                else
                    right=mid-1;
            }
            else
            {
                if(nums[left]<=target&&target<nums[mid])
                    right=mid-1;
                else
                    left=mid+1;
            }
        }   
        return -1; 
    }
};

你可能感兴趣的:(leetcode,c++)