首页 > 代码库 > 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?

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

#include <vector>
#include <string>
using std::string;
using std::vector;
class Solution 
{
public:
	bool search(int A[], int n, int target) 
	{
		if(n==0)
			return false;
		int loc = find_max(A,n);
		bool flag = binary_search(A,0,loc,target);
		if(flag)
			return flag;
		flag = binary_search(A,loc+1,n-1,target);
		return flag;
	}
	int find_max(int* a, int n)
	{
		for(int i=0; i<n-1; i++)
		{
			if(a[i] > a[i+1])
				return i;
		}
		return 0;
	}
	bool binary_search(int* a, int low, int high, int target)
	{
		while(low<=high)
		{
			int mid = (low+high)/2;
			if(a[mid] > target)
				high--;
			else if(a[mid] < target)
				low++;
			else
				return true;
		}
		return false;
	}
};


LeetCode--Search in Rotated Sorted Array II