mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 12:04:37 +08:00
【875. 爱吃香蕉的珂珂】【C++】
【875. 爱吃香蕉的珂珂】【C++】
This commit is contained in:
@ -171,7 +171,43 @@ for (int i = 0; i < n; i++)
|
||||
|
||||
======其他语言代码======
|
||||
|
||||
#### c++
|
||||
[cchroot](https://github.com/cchroot) 提供 C++ 代码:
|
||||
|
||||
```c++
|
||||
class Solution {
|
||||
public:
|
||||
int minEatingSpeed(vector<int>& piles, int H) {
|
||||
// 二分法查找最小速度
|
||||
// 初始化最小速度为 1,最大速度为题目设定的最大值 10^9
|
||||
// 这里也可以遍历 piles 数组,获取数组中的最大值,设置 right 为数组中的最大值即可(因为每堆香蕉1小时吃完是最快的)
|
||||
// log2(10^9) 约等于30,次数不多,所以这里暂时就不采取遍历获取最大值了
|
||||
int left = 1, right = pow(10, 9);
|
||||
while (left < right) { // 二分法基本的防止溢出
|
||||
int mid = left + (right - left) / 2;
|
||||
// 以 mid 的速度吃香蕉,是否能在 H 小时内吃完香蕉
|
||||
if (!canFinish(piles, mid, H))
|
||||
left = mid + 1;
|
||||
else
|
||||
right = mid;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
// 以 speed 的速度是否能把香蕉吃完
|
||||
bool canFinish(vector<int>& piles, int speed, int H) {
|
||||
int time = 0;
|
||||
// 遍历累加时间 time
|
||||
for (int p: piles)
|
||||
time += (p - 1) / speed + 1;
|
||||
return time <= H; // time 小于等于 H 说明能在 H 小时吃完返回 true, 否则返回 false
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### python
|
||||
[tonytang731](https://https://github.com/tonytang731) 提供 Python3 代码:
|
||||
|
||||
```python
|
||||
import math
|
||||
|
||||
|
Reference in New Issue
Block a user