码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Search in Rotated Sorted Array II

时间:2015-01-13 12:33:11      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:leetcode   search   binary search   

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

标签:leetcode   search   binary search   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!