2022/01/20 - 875. Koko Eating Bananas
875. Koko Eating Bananas - Medium
运用了二分查找法,稍微根据题目变动一点点。
Description¶
875. Koko Eating Bananas
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.
Example 1:
Input: piles = [3,6,7,11], h = 8 Output: 4
Example 2:
Input: piles = [30,11,23,4,20], h = 5 Output: 30
Example 3:
Input: [1,1,1,999999999] Output: 142857143
这道题呢稍微有点 tricky,我一开始想的是找到话费的时间刚好等于h
的数值就行了,结果[1,1,1,999999999]
输入瞬间打我脸,所以我就想,如果数字非常大的情况下,肯定是会有很多种输出结果是一样,而这道题是要找最小的那个值,所以当我计算到total
值等于h
的时候,无脑将right = mid - 1
,然后继续尝试,直到left
和right
相等的时候,就是最小值啦。
Solution¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|