珂珂喜歡吃香蕉烟馅。這里有 n 堆香蕉,第 i 堆中有 piles[i] 根香蕉玖像。警衛(wèi)已經(jīng)離開了,將在 h 小時后回來齐饮。
珂珂可以決定她吃香蕉的速度 k (單位:根/小時)捐寥。每個小時,她將會選擇一堆香蕉祖驱,從中吃掉 k 根握恳。如果這堆香蕉少于 k 根,她將吃掉這堆的所有香蕉羹膳,然后這一小時內(nèi)不會再吃更多的香蕉睡互。
珂珂喜歡慢慢吃,但仍然想在警衛(wèi)回來前吃掉所有的香蕉陵像。
返回她可以在 h 小時內(nèi)吃掉所有香蕉的最小速度 k(k 為整數(shù))就珠。
示例 1:
輸入:piles = [3,6,7,11], h = 8
輸出:4。
package 二分;
import java.util.Arrays;
//leetcode submit region begin(Prohibit modification and deletion)
class KokoEatingBananas875 {
int[] piles;
int h;
public boolean isMatch (int val) {
int count = 0;
for (int i = piles.length-1; i >=0; i--) {
if (piles[i] / val == 0) {
count += 1;
}
else if (piles[i] % val == 0) {
count += piles[i]/val;
} else {
count += piles[i]/val + 1;
}
if (count > h) {
return false;
}
}
return true;
}
public int minEatingSpeed(int[] piles, int h) {
this.piles = piles;
this.h = h;
Arrays.sort(piles);
int left = 0;
int right = piles[piles.length-1];
int mid;
while (left < right) {
mid = (left+right) / 2;
if (isMatch(mid)) {
right = mid;
if (mid == 1) {
return 1;
}
if (!isMatch(mid-1)) {
return mid;
}
} else {
left = mid+1;
}
}
return left;
}
public static void main(String[] args) {
KokoEatingBananas875 so = new KokoEatingBananas875();
int a = so.minEatingSpeed(new int[]{
2,2
}, 2);
int b = 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)