#include <iostream>
#include <vector>
using namespace std;
/*
Search in rotated sorted array II
允许有重复数据
*/
int Solution(vector<int> &vec,int target)
{
if (0 == vec.size())
return -1;
int first = 0;
int last = vec.size();
while (first != last)
{
int quote = first + (last - first) / 2;
if (target == vec[quote])
return quote;
if (vec[first] < vec[quote])
{
if (vec[first] <= target&& target < vec[quote])
{
last = quote;
}
else
{
first = quote+1;
}
}
else if(vec[first] > vec[quote])
{
if (vec[quote] < target&& target <= vec[last-1])
{
first = quote+1;
}
else
{
last = quote;
}
}
else
{
first++;
}
}
return -1;
}
int main()
{
int arr[] = { 6,7,8,9,0,5,5,5,5,5 };
vector<int> vec(&arr[0], &arr[10]);
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
int target_index = Solution(vec,5);
if (-1 == target_index)
cout << "can not find it" << endl;
else
cout << "find it,index is "<< target_index << endl;
system("pause");
return 0;
}
#include <vector>
using namespace std;
/*
Search in rotated sorted array II
允许有重复数据
*/
int Solution(vector<int> &vec,int target)
{
if (0 == vec.size())
return -1;
int first = 0;
int last = vec.size();
while (first != last)
{
int quote = first + (last - first) / 2;
if (target == vec[quote])
return quote;
if (vec[first] < vec[quote])
{
if (vec[first] <= target&& target < vec[quote])
{
last = quote;
}
else
{
first = quote+1;
}
}
else if(vec[first] > vec[quote])
{
if (vec[quote] < target&& target <= vec[last-1])
{
first = quote+1;
}
else
{
last = quote;
}
}
else
{
first++;
}
}
return -1;
}
int main()
{
int arr[] = { 6,7,8,9,0,5,5,5,5,5 };
vector<int> vec(&arr[0], &arr[10]);
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
int target_index = Solution(vec,5);
if (-1 == target_index)
cout << "can not find it" << endl;
else
cout << "find it,index is "<< target_index << endl;
system("pause");
return 0;
}