LeetCode81 Search in Rotated Sorted Array II 搜索旋转有序序列II C++

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?

题源:here;完整实现:here

思路:

第33题,但是因为允许出现重复的数,这样会影响区间的判断,所以我们需要排除首尾相同的情况,余下的不用改变。代码如下:

class Solution {
public:
	bool search(vector<int>& nums, int target) {
		while (nums[0] == nums[nums.size() - 1] && nums.size() > 1) 
			nums.erase(nums.begin());
		int left = 0, right = nums.size() - 1;

		while (left <= right){
			int idx = (left + right) / 2;
			if (nums[idx] == target) return true;
			if (nums[idx] >= nums[0] && target < nums[0]) left = idx + 1;
			else if (nums[idx] >= nums[0] && target >= nums[0]){
				if (nums[idx] > target) right = idx - 1;
				else left = idx + 1;
			}
			else if (nums[idx] < nums[0] && target < nums[0]){
				if (nums[idx] > target) right = idx - 1;
				else left = idx + 1;
			}
			else right = idx - 1;
		}

		return false;
	}
};

 
 
 
 


扫描二维码关注公众号,回复: 2163859 查看本文章

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80976284