手撕LeetCode-数组-二分查找
二分查找的模板
int search(int[]nums,int traget){
int left=0,right=nums.length-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]==traget){
return mid;}
else if(traget<nums[mid]){
right=mid-1;}
else{
left=mid+1;}
}
}
具体例题-爱吃香蕉的珂珂
public int minEatingSpeed(int[] piles,int H){
int left=1,right=getMax(piles)+1;
while(left<right){
int mid =left+(right-left)/2;
if(canFinsh(piles,mid,H))
{
right= mid;
}else{
left=mid+1;
}
}
return left;
}
public boolean canFinsh(int[] piles,int speed,int H){
int time=0;
for(int n : piles){
time=time+timeof(n,speed);
}
return time<=H;
}
public int timeof(int n,int speed){
return (n/speed)+((n%speed>0)?1:0);
}
public int getMax(int[]piles){
int max=0;
for(int n:piles){
max=Math.max(n,max);
}
return max;
}