33. Search in Rotated Sorted Array *HARD*

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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*的主要内容,如果未能解决你的问题,请参考以下文章

33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array *HARD*

33. Search in Rotated Sorted Array

Leetcode[33]-Search in Rotated Sorted Array

LC.33. Search in Rotated Sorted Array

#Leetcode# 33. Search in Rotated Sorted Array