LeetCode Search in Rotated Sorted Array II

LeetCode 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?

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.


这一题在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)的复杂度。

Leave a Reply

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