标签:binary search
题目
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k such that she can eat all the bananas within h hours.
Input: piles = [3,6,7,11], h = 8
Output: 4
Constraints:
1 <= piles.length <= 104piles.length <= h <= 1091 <= piles[i] <= 109
解答
- Brute Force: 从k = 1开始递增判断k是否满足条件,最坏情况的时间复杂度为O(nm),m为香蕉堆的最大值
- 其实K值的分布由小到大是 ...000000111111... ;0代表满足条件,1代表不满足条件,该分布代表可以用二分查找来优化,初始时left = 0, right = m, 最坏情况时间复杂度为O(nlog(m))
class Solution {
public int minEatingSpeed(int[] piles, int h) {
Arrays.sort(piles);
int right = piles[piles.length - 1];
int left = 1;
int k = 1;
while(left < right) {
k = (left + right)/2;
int thish = 0;
for (int pile: piles) {
if (pile < k) {
thish++;
} else {
thish += Math.ceil((double) pile/k);
}
if (thish > h) {
break;
}
}
if (thish <= h) {
right = k;
} else if (thish >= h) {
left = k + 1;
} else {
return k;
}
}
return left;
}
}