class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size()==1){if(target==nums[0]) return 0;else return -1;}
if(nums.size()==2){if(target==nums[0]) return 0;else if(target==nums[1]) return 1;else return -1;}
int changed=0;
int pivot=0;
for(int i=2;i<nums.size();i++){
if((nums[i]-nums[i-1])*(nums[i-1]-nums[i-2])<0){
changed=1;pivot=i;break;
}
}
int l=nums.size();
if(changed==0){return binarySearch(nums,target,0,l-1);}
if(binarySearch(nums,target,0,pivot-1)!=-1){return binarySearch(nums,target,0,pivot-1);}
else return binarySearch(nums,target,pivot,l-1);
}
private:
int binarySearch(vector<int> &nums,int target,int a,int b){
if(nums.size()==0) return -1;
if(a==b){
if(target==nums[a]){return a;}
else{return -1;}
}
if(b-a==1){
if(target==nums[a]){return a;}
else if(target==nums[b]){return b;}
else return -1;
}
if(target==nums[(a+b)/2]){
return (a+b)/2;
}
if(target>nums[(a+b)/2]){
return binarySearch(nums,target,((a+b)/2)+1,b);
}
if(target<nums[(a+b)/2]){
return binarySearch(nums,target,a,((a+b)/2)-1);
}
}
};
查找可采用二分,时间复杂度为logN,然而二分的前提为数组是有序的,此时需找出有序数列的断点,断点的左右序列都是有序的,分别进行二分查找即可。