![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e4fe23c837e9b1bebd68753e0aed6a23.png)
遍历 O(n)
java 二分 logn
class Solution {
//数组里面的数互不相同
public int search(int[] nums, int target) {
int len = nums.length;
int l = 0,r = len-1;
if(len == 1){
if(target == nums[0]) return 0;
else return -1;
}
while(l <= r){
int mid = (l+r)/2;
if(nums[mid] == target) return mid;
//第一种情况
if(nums[0] <= nums[mid]){
//如果target比mid大,只能去右边搜索
if(target > nums[mid]){
l = mid+1;
}
//如果target比mid小,有两种情况,再判断,是去左边还是右边
if(target < nums[mid]){
//如果target比nums[0]还要小,那么去右边搜索
if(target < nums[0]) l = mid + 1;
//若果target比nums[0]大,那么target就在nums[0]和nums[mid]之间
if(target >= nums[0]) r = mid-1;
}
}
//第二种情况
if(nums[0] > nums[mid]){
//如果目标值比target小,只能去左边搜索
if(target < nums[mid]) r = mid-1;
//如果目标值比target大,有两种情况,可能在左边也可能在右边
if(target > nums[mid]){
//在左边
if(target >= nums[0]) r = mid-1;
//在右边
if(target < nums[0]) l = mid+1;
}
}
}
return -1;
}
}
C++ log(N)
class Solution {
public:
/**
* nums数组本身不有序
*/
int search(vector<int>& nums, int target) {
int len = nums.size();
int l = 0, r = len-1;
while(l <= r){
int mid = l + (r-l)/2;
if(nums[mid] == target) return mid;
if(nums[0] <= nums[mid]){
if(target > nums[mid]) l = mid+1;
if(target < nums[mid]){
if(target >= nums[0]) r = mid-1;
else l = mid + 1;
}
}else{
if(target < nums[mid]) r = mid-1;
if(target > nums[mid]){
if(target < nums[0]) l = mid+1;
if(target >= nums[0]) r = mid-1;
}
}
}
return -1;
}
};