leetcode 7. 在有序可重复数组旋转后搜寻 Search in Rotated Sorted Array II

leetcode 7. 在有序可重复数组旋转后搜索 Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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

解题思路:
本题基于leetcode 6. 在有序数组旋转后搜索 Search in Rotated Sorted Array,允许有序数组中存在重复。
与上一题(不允许重复)的不同是
nums[m] > nums[l] : (l, m-1)单增
nums[m] <= nums[l] : (m+1, r)不一定单增,因为{1,3,1,1,1} 或{1,1,1,3,1}

此时,可以将上述条件分开来看
nums[m] < nums[l] : (m+1, r)一定单增
num[m] == nums[l] : 将 l+1,重新递归计算 (当[l, r],将 r-1

class Solution {
public:
    //nums 数组边界为 [l,r)
    bool searchR(vector<int>& nums,int l, int r, int target) {
        if (r <= l)
            return false;
        int m = (l+r) / 2;
        if (nums[m] == target)
            return true;

        if (nums[l] < nums[m]) {
            if (target >= nums[l] && target < nums[m])
                return searchR(nums, l, m, target);
            else
                return searchR(nums, m+1, r, target);
        } else if (nums[l] > nums[m]) {
            if(target > nums[m] && target <= nums[r-1])
                return searchR(nums, m+1, r, target);
            else
                return searchR(nums, l, m, target);    
        } else {
            return searchR(nums, ++l, r, target);    

        }
    }

    bool search(vector<int>& nums, int target) {
        return searchR(nums, 0, nums.size(), target);
    }
};