Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

Suppose an array sorted in ascending order 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).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

解题技巧:

方法一:先找到旋转的位置,再利用二分查找法判断目标是否存在。

代码:

bool Find(vector& nums, int left, int right, int target)
{
    if(left > right) return false;

    int mid = (left + right) / 2;

    if(nums[mid] == target) return true;
    if(nums[mid] > target)
    {
        right = mid - 1;
    }
    else
    {
        left = mid + 1;
    }
    return Find(nums, left, right, target);
}

bool search(vector& nums, int target)
{
    int t = 0;
    bool res;
    for(int i = 1; i < nums.size(); i ++)
    {
        if(nums[i-1] > nums[i])
        {
            t = i-1;
            break;
        }
    }
   
    res = Find(nums, 0, t, target)|| Find(nums, t+1, nums.size()-1, target);
    return res;
}


你可能感兴趣的:(leetcode)