您的位置:首页 > 其它

LeetCode--Search in Rotated Sorted Array II

2015-01-13 11:35 351 查看
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;
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: