LeetCode Search in Rotated Sorted Array II

81. 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,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

这一题在LeetCode Search in Rotated Sorted Array的基础上,增加了数组有重复元素的约束,其实相当于LeetCode Search in Rotated Sorted ArrayLeetCode Find Minimum in Rotated Sorted Array II的结合,搜索框架采用前者(即先找到有序的半个部分,再决定丢弃哪半个部分),边界判断采用后者(即遇到中间和边缘相等时,移动边缘)。代码上只是在前者代码的基础上增加了一个else分支。完整代码如下:

class Solution {
public:
    bool search(vector<int>& nums, int target)
    {
        int l = 0, r = nums.size() – 1;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target)
                return true;
            if (nums[mid] < nums[r]) {
                if (target > nums[mid] && target <= nums[r]) {
                    l = mid + 1;
                }
                else {
                    r = mid – 1;
                }
            }
            else if (nums[mid] > nums[r]) {
                if (target >= nums[l] && target < nums[mid]) {
                    r = mid – 1;
                }
                else {
                    l = mid + 1;
                }
            }
            else {
                –r;
            }
        }
        return false;
    }
};

本代码提交AC,用时12MS。因为多了一个else分支,算法最坏情况下,会达到O(n)的复杂度。

二刷。思路相同,使用递归实现,代码如下:

class Solution {
public:
	bool SearchRange(vector<int>& nums, int l, int r, int target) {
		if (l > r)return false;
		if (l == r)return nums[l] == target;

		int mid = l + (r - l) / 2;
		if (nums[mid] == target)return true;

		if (nums[l] < nums[mid]){
			if (target >= nums[l] && target < nums[mid])return SearchRange(nums, l, mid - 1, target);
			else return SearchRange(nums, mid + 1, r, target);
		}
		else if (nums[l] > nums[mid]) {
			if (target > nums[mid] && target <= nums[r])return SearchRange(nums, mid + 1, r, target);
			else return SearchRange(nums, l, mid - 1, target);
		}
		else {
			++l;
			return SearchRange(nums, l, r, target);
		}
	}
	bool search(vector<int>& nums, int target) {
		return SearchRange(nums, 0, nums.size() - 1, target);
	}
};

本代码提交AC,用时4MS。

Leave a Reply

Your email address will not be published. Required fields are marked *