LeetCode-875. Koko Eating Bananas

网友投稿 678 2022-08-25

LeetCode-875. Koko Eating Bananas

LeetCode-875. Koko Eating Bananas

Koko loves to eat bananas.  There are ​​N​​​ piles of bananas, the ​​i​​​-th 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 won't eat any more bananas during this hour.

Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.

Return the minimum integer ​​K​​​ such that she can eat all the bananas within ​​H​​ hours.

Example 1:

Input: piles = [3,6,7,11], H = 8Output: 4

Example 2:

Input: piles = [30,11,23,4,20], H = 5Output: 30

Example 3:

Input: piles = [30,11,23,4,20], H = 6Output: 23

Note:

​​1 <= piles.length <= 10^4​​​​piles.length <= H <= 10^9​​​​1 <= piles[i] <= 10^9​​

题解:

第一次超时,不可顺序查找

class Solution {public: int minEatingSpeed(vector& piles, int H) { int n = piles.size(); int mink = 0; for (int k = 1; ; k++) { double sum = 0; for (int i = 0; i < n; i++) { int idx = piles[i] / k; sum += idx; if (piles[i] % k != 0) { sum++; } } if (sum <= H) { mink = k; break; } } return mink; }};

改用二分查找AC:

class Solution {public: int minEatingSpeed(vector& piles, int H) { sort(piles.begin(), piles.end()); int n = piles.size(); if (n == 0) { return 0; } if (n == 1) { return (piles[0] + H - 1) / H; } if (n == H) { return piles[n - 1]; } int left = 0, right = piles[n - 1]; while (left <= right) { int mid = (left + right) / 2; int sum = 0; for (int i = 0; i < n; i++) { sum += piles[i] / mid; if (piles[i] % mid != 0) { sum++; } } if (sum <= H) { right = mid - 1; } else { left = mid + 1; } } return left; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-1296. Divide Array in Sets of K Consecutive Numbers
下一篇:LeetCode-1276. Number of Burgers with No Waste of Ingredients
相关文章

 发表评论

暂时没有评论,来抢沙发吧~