题目描述
狒狒喜欢吃香蕉。这里有 N
堆香蕉,第 i
堆中有 piles[i]
根香蕉。警卫已经离开了,将在 H
小时后回来。
狒狒可以决定她吃香蕉的速度 K
(单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K
根。如果这堆香蕉少于 K
根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉,下一个小时才会开始吃另一堆的香蕉。
狒狒喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。
返回她可以在 H
小时内吃掉所有香蕉的最小速度 K
(K
为整数)。
示例 1:
输入: piles = [3,6,7,11], H = 8
输出: 4
示例 2:
输入: piles = [30,11,23,4,20], H = 5
输出: 30
示例 3:
输入: piles = [30,11,23,4,20], H = 6
输出: 23
提示:
1 <= piles.length <= 10^4
piles.length <= H <= 10^9
1 <= piles[i] <= 10^9
注意:本题与主站 875 题相同: https://leetcode.cn/problems/koko-eating-bananas/
解法
方法一
| class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
left, right = 1, max(piles)
while left < right:
mid = (left + right) >> 1
s = sum((pile + mid - 1) // mid for pile in piles)
if s <= h:
right = mid
else:
left = mid + 1
return left
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | class Solution {
public int minEatingSpeed(int[] piles, int h) {
int mx = 0;
for (int pile : piles) {
mx = Math.max(mx, pile);
}
int left = 1, right = mx;
while (left < right) {
int mid = (left + right) >>> 1;
int s = 0;
for (int pile : piles) {
s += (pile + mid - 1) / mid;
}
if (s <= h) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int left = 1, right = *max_element(piles.begin(), piles.end());
while (left < right) {
int mid = left + right >> 1;
int s = 0;
for (int pile : piles) s += (pile + mid - 1) / mid;
if (s <= h)
right = mid;
else
left = mid + 1;
}
return left;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | func minEatingSpeed(piles []int, h int) int {
left, right := 1, slices.Max(piles)
for left < right {
mid := (left + right) >> 1
s := 0
for _, pile := range piles {
s += (pile + mid - 1) / mid
}
if s <= h {
right = mid
} else {
left = mid + 1
}
}
return left
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | public class Solution {
public int MinEatingSpeed(int[] piles, int h) {
int left = 1, right = piles.Max();
while (left < right)
{
int mid = (left + right) >> 1;
int s = 0;
foreach (int pile in piles)
{
s += (pile + mid - 1) / mid;
}
if (s <= h)
{
right = mid;
}
else
{
left = mid + 1;
}
}
return left;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | class Solution {
func minEatingSpeed(_ piles: [Int], _ h: Int) -> Int {
var left = 1
var right = piles.max() ?? 0
while left < right {
let mid = (left + right) / 2
var hours = 0
for pile in piles {
hours += (pile + mid - 1) / mid
}
if hours <= h {
right = mid
} else {
left = mid + 1
}
}
return left
}
}
|