C++代码:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
int sz = nums.size();
int l = 0;
int r = sz-1;
int mid;
while (l<=r)
{
mid = (l+r)/2;
if (nums[mid] == target)
return mid;
//左半部分有序
else if (nums[mid] >= nums[l])
{
//如果target在左半部分
if (nums[l] <= target && nums[mid] > target)
r = mid-1;
//如果在不在左半部分
else
l = mid + 1;
}
//此时(nums[mid] < nums[l]),右半部分有序
else
{
//如果在右半部分
if (nums[mid] < target && nums[r] >= target)
l = mid+1;
//如果不在右半部分
else
r = mid - 1;
}
}
return -1;
}
};
int main()
{
Solution s;
vector<int> v;
/*v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
v.push_back(8);
v.push_back(9);
v.push_back(0);
v.push_back(1);
v.push_back(2);*/
v.push_back(3);
v.push_back(1);
cout<<s.search(v, 1)<<endl;
return 0;
}