首页 > 其他 > 详细

LeetCode--Search in Rotated Sorted Array II

时间:2015-01-13 12:31:04      阅读:145      评论:0      收藏:0      [点我收藏+]

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

原文:http://blog.csdn.net/shaya118/article/details/42674433

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!