R8-二分查找篇
等等,不是?O(logn)?那岂不是一次遍历数组都超时了hh.
二分查找+分类
class Solution {
public int search(int[] nums, int target) {
if (nums==null||nums.length==0){
return -1;
}
int start=0;
int end=nums.length-1;
int mid;
while (start<=end){
mid=(start+end)/2;
if (target==nums[mid]){
return mid;
}
//前半段有序
if (nums[start]<=nums[mid]){
if (target>=nums[start]&&target<nums[mid]){
end=mid-1;
}else{
start=mid+1;
}
}
//后半段有序
else{
if (target<=nums[end]&&target>nums[mid]){
start=mid+1;
}else{
end=mid-1;
}
}
}
return -1;
}
}
ps:
1.
2.java不能连续的等号或者大于小于号,python可以