Fork me on GitHub

81. Search in Rotated Sorted Array II

81. 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.

解析

  • 和Search in Rotated Sorted Array唯一的区别是这道题目中元素会有重复的情况出现。不过正是因为这个条件的出现,出现了比较复杂的case,甚至影响到了算法的时间复杂度。原来我们是依靠中间和边缘元素的大小关系,来判断哪一半是不受rotate影响,仍然有序的。而现在因为重复的出现,如果我们遇到中间和边缘相等的情况,我们就丢失了哪边有序的信息,因为哪边都有可能是有序的结果。假设原数组是{1,2,3,3,3,3,3},那么旋转之后有可能是{3,3,3,3,3,1,2},或者{3,1,2,3,3,3,3},这样的我们判断左边缘和中心的时候都是3,如果我们要寻找1或者2,我们并不知道应该跳向哪一半。解决的办法只能是对边缘移动一步,直到边缘和中间不在相等或者相遇,这就导致了会有不能切去一半的可能。

 // The array may contain duplicates.
	bool search(vector<int>& nums, int target) {
if (nums.empty())
		{
			return false;
		}
		int low = 0, high = nums.size() - 1;
		int mid = 0;
		while (low<=high)
		{
			mid = low + (high - low) / 2;
			if (nums[mid]==target)
			{
				return true;	
			}
			if (nums[mid]>nums[high]) // 前半部分有序;后半部分无序
			{
				if (nums[mid]>target&&nums[low]<=target)
				{
					high = mid-1;
				}
				else
				{
					low = mid + 1;
				}
			}
			else if (nums[mid]<nums[high]) // 后半部分有序
			{
				if (nums[mid]<target&&target<=nums[high])
				{
					low = mid+1;
				}
				else
				{
					high = mid-1;
				}
			}
			else
			{
				high--; //与high在比较
			}
		}
		return false;
	}

// 81. Search in Rotated Sorted Array II
class Solution_81 {
public:
	// The array may contain duplicates.
	bool search_(vector<int>& nums, int target) {

		if (nums.empty())
		{
			return false;
		}
		int low = 0, high = nums.size() - 1;
		int mid = 0;
		while (low<high)
		{
			mid = low + (high - low) / 2;
			if (nums[mid]==target)
			{
				return true;	
			}
			if (nums[mid]>nums[high]) // 前半部分有序;后半部分无序
			{
				if (nums[mid]>target&&nums[low]<=target)
				{
					high = mid;
				}
				else
				{
					low = mid + 1;
				}
			}
			else if (nums[mid]<nums[high]) // 后半部分有序
			{
				if (nums[mid]<target&&target<=nums[high])
				{
					low = mid+1;
				}
				else
				{
					high = mid;
				}
			}
			else
			{
				high--;
			}
		}
		return nums[low] == target ? true : false;
	}

	bool search(int A[], int n, int target) {
		vector<int> vec(A, A + n);
		return search_(vec, target);
	}
};

题目来源

posted @ 2018-04-07 21:10  ranjiewen  阅读(142)  评论(0编辑  收藏  举报