二分查找
class Solution {
public int minEatingSpeed(int[] piles, int h) {
/**
* Arrays.stream(arr).max().getAsInt()方法获取数组最大值
*/
int minSpeed = 1;
int maxSpeed = Arrays.stream(piles).max().getAsInt();
/**
* 使用二分查找法,最小速度肯定在[minSpeed, maxSpeed]之间,其花费的时间为小于等于h的最大值
*/
while (minSpeed < maxSpeed) {
int speed = minSpeed + (maxSpeed - minSpeed) / 2;
if (time(speed, piles) > h){
minSpeed = speed + 1;
}
else {
maxSpeed = speed;
}
}
return minSpeed;
}
public int time(int speed, int[] piles){
int res = 0;
for (int i = 0; i < piles.length; i++) {
/**
* 时间需要向上取整,同时要变成double型,防止精度遗失
*/
res += Math.ceil(piles[i] / 1.0 / speed);
}
return res;
}
}
/**
* 时间复杂度 O(nlogn)
* 空间复杂度 O(1)
*/
https://leetcode-cn.com/problems/koko-eating-bananas/