标签:c++ leetcode binary search array

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.
//vs2012测试代码
#include<iostream>
using namespace std;
#define N 8
//classified discussion
//1. Based on the property of rotated array, there may or may not have one sorted sequence
//when one sequence is divided into two parts
//2. make decision under all these cases
class Solution {
public:
bool search(int A[], int n, int target)
{
if( n==0 )
return false;
int mid = 0;
int left=0, right=n-1;
while( left <= right)
{
mid = left + (right-left)/2 ;
if(A[mid] == target)
return true;
if( A[left] < A[mid] ) //left side sorted, including mid, it is sorted in [l,mid]
{
if( A[left] <= target && target < A[mid] )
right = mid - 1;
else
left = mid + 1;
}
else if ( A[mid] < A[right] ) //right side sorted, [mid,r] must be sorted, if [l,mid] not sorted
{
if ( A[mid] < target && target <= A[right] )
left = mid + 1;
else
right = mid - 1;
}
else if ( A[left] == A[mid] ) //A[m] is not the target, so remove en element equal to A[m] is safe
left++;
else if ( A[right] == A[mid] ) //ditto
right--;
}
return false;
}
};
int main()
{
int A[N];
int a , target;
for(int i=0; i<N; i++)
{
cin>>a;
A[i] = a;
}
cin>>target;
Solution lin;
cout<<lin.search( A,N,target)<<endl;
return 0;
}//方法一:自测Accepted
//classified discussion
//1. Based on the property of rotated array, there may or may not have one sorted sequence
//when one sequence is divided into two parts
//2. make decision under all these cases
class Solution {
public:
bool search(int A[], int n, int target)
{
if( n==0 )
return false;
int mid = 0;
int left=0, right=n-1;
while( left <= right)
{
mid = left + (right-left)/2 ;
if(A[mid] == target)
return true;
if( A[left] < A[mid] ) //left side sorted, including mid, it is sorted in [l,mid]
{
if( A[left] <= target && target < A[mid] )
right = mid - 1;
else
left = mid + 1;
}
else if ( A[mid] < A[right] ) //right side sorted, [mid,r] must be sorted, if [l,mid] not sorted
{
if ( A[mid] < target && target <= A[right] )
left = mid + 1;
else
right = mid - 1;
}
else if ( A[left] == A[mid] ) //A[m] is not the target, so remove en element equal to A[m] is safe
left++;
else if ( A[right] == A[mid] ) //ditto
right--;
}
return false;
}
};leetcode_81_Search in Rotated Sorted Array II
标签:c++ leetcode binary search array
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43638543