虽然二分查找听起来很简单但是实际并不简单
递归方法:
int binarysearch(int[] arr, int l,int r,int x){
if(l<=r){
int mid = l+(r-l)>>>1;
if(arr[mid]==x)
return mid;
if(arr[mid]>x)
return binarysearch(arr,l,mid-1,x);
return binarysearch(arr,mid+1,r,x);
}
return -1;
}
非递归方法:
int binarysearch(int [] arr, int x){
int l =0;
int right = arr.length-1;
while(l<=r){
int mid=l+(r-l)>>>1;
if(arr[mid]==x)
return mid;
if(arr[mid]>x)
r=mid-1;
else
l=mid+1;
}
return -1;
}
题解:排除法(双指针) + 二分法(Python 代码、Java 代码) - 力扣(LeetCode)
这里有一个其他的二分查找,写的比较全,但是我认为没有必要,因为如果不是mid直接排除就好了,为何还要计算在内。
leetcode410
面试的时候通常会把二分查找和其他的结合起来考,把二分查找当作一种优化方式
![68d6f5a64426e88f119e6c5dad2aaf2c.png](https://img-blog.csdnimg.cn/img_convert/68d6f5a64426e88f119e6c5dad2aaf2c.png)
这个题目,就是找能够覆盖的区间
区间长度最暴力的方法就是先从a[i] 开始,a[1] a[2] a[3] a[4]
逐渐增加长度。
每次计算去优化。时间复杂度是n2
但是长度增加如此缓慢就不太好了,用二分可以将时间复杂度缩短为nlogn.
首先想最小多少?
a[0].......a[n]中的最小值
最大多少
a[0]+.....a[n]
以这两个点当作l和r去计算
注意:
1 越界问题 用long盛装数字
2 返回值边界问题,什么时候符合条件,返回,这里不能直接返回符合条件的mid 因为可能比他小的也符合条件,所以我们要做的是记录下来符合条件的mid的最小值。 用一个ans去记录
用二分非递归模版
long ans=r;
while(l<r){
int temp=(r-l)>>1;
int mid=temp+l;
int count=1;//important start is 1
//handle to calculate count
********
//l<=r important "="
while(l<=r){
if(count>m){
//*****not satisfy condition
l=mid+1;
}else{
//***satisfy condition and need to see if there is a better solution
ans=ans>mid?mid:ans;
r=mid-1;
}
}
}
return ans;
注意:这里如果不能确定一定可以找到count=mid则不要把他单独拎出来,出现:
if(count==m)
ans=Math.min(ans,mid);
只要找到区间就好。
完整代码:
class Solution {
public int splitArray(int[] nums, int m) {
//here should be long in case it out of memory
long l=0;
long r=0;
for(int i=0;i<nums.length;i++){
l=l<nums[i]?nums[i]:l;
r+=nums[i];
}
long ans=r;
//<=
while(l<=r){
//handle
long min=(r-l)>>1;
long mid=min+l;
long sum=0;
int count=1;//important start is 1
for(int i=0;i<nums.length;i++){
if(sum+nums[i]>mid){
count++;
sum=nums[i];
}else{
sum+=nums[i];
}
}
if(count>m){
l=mid+1;
}else{
//when in this loop means mid could become one answer so we need the small one. (when count is 2 and m is 3 is also a answer.)
r=mid-1;
}
}
return (int)ans;
}
}