33. Search in Rotated Sorted Array *HARD*

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

利用二分查找的思想。

int binary_search(vector<int>& nums, int left, int right, int target)
{
    if(left > right)
        return -1;
    while(left <= right)
    {
        int mid = (left+right)>>1;
        if(nums[mid] == target)
            return mid;
        else if(nums[mid] < target)
            left = mid+1;
        else
            right = mid-1;
    }
    return -1;
}
int search(vector<int>& nums, int target) {
    int n = nums.size(), left = 0, right = n-1, mid;
    if(left == right && nums[0] == target)
        return 0;
    while(left <= right)
    {
        mid = (left+right)>>1;
        if(target == nums[mid])
            return mid;
        if(nums[left] <= nums[mid])
        {
            if(target >= nums[left] && target <= nums[mid])
                return binary_search(nums, left, mid, target);
            left = mid+1;
        }
        else
        {
            if(target >= nums[mid] && target <= nums[right])
                return binary_search(nums, mid, right, target);
            right = mid-1;
        }
    }
    return -1;
}

 

你可能感兴趣的:(33. Search in Rotated Sorted Array *HARD*)