[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 = 8
Output: 4

Example 2:

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

Example 3:

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

Constraints:

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

爱吃香蕉的珂珂。

题意是有一个猴子和 N 堆香蕉,每堆香蕉有 piles[i] 根,警卫会在 H 小时候返回,所以猴子有 H 小时吃香蕉。猴子可以决定自己吃香蕉的速度 K。每个小时,她会选择一个堆,吃掉其中的 K 根香蕉。如果这堆香蕉小于 K 根,则猴子会把这堆香蕉全吃掉并在当前这个小时内不再吃别的堆上的香蕉。请返回一个最小速度 K,保证猴子可以在 H 小时内把所有香蕉吃掉。

思路是二分法。这里题目的限制条件的最后一条规定了 piles[i] 不会大于10的九次方,所以二分法的上界我直接就取了 10^9。这里二分是在分猴子吃香蕉的速度。二分法得到某一个速度 mid 之后,去计算吃掉所有香蕉需要花费的时间。这里我们需要额外写一个函数去做计算时间的工作。在这个计算时间的函数里,对于某一堆香蕉,如果香蕉数 % 速度 不等于0,那么意味着时间需要 + 1。例子,比如吃的速度是 3,但是香蕉有10个,那么就必须分4个小时吃完。如果计算出来的时间小于H则说明速度快了,需要往左半边走,减慢速度;反之则往右半边走,加快速度。二分法的 while 循环退出的那一刻,low就是满足题意的最小速度。

时间O(logn)

空间O(1)

Java实现

 1 class Solution {
 2     public int minEatingSpeed(int[] piles, int H) {
 3         int low = 1;
 4         int high = 1000000000;
 5         while (low <= high) {
 6             int mid = low + (high - low) / 2;
 7             int hour = getHour(piles, mid);
 8             if (hour <= H) {
 9                 high = mid - 1;
10             } else {
11                 low = mid + 1;
12             }
13         }
14         return low;
15     }
16 
17     private int getHour(int[] piles, int speed) {
18         int res = 0;
19         for (int p : piles) {
20             res += p / speed;
21             if (p % speed != 0) {
22                 res++;
23             }
24         }
25         return res;
26     }
27 }

相关题目

410. Split Array Largest Sum

774. Minimize Max Distance to Gas Station

875. Koko Eating Bananas

1011. Capacity To Ship Packages In N Days

1060. Missing Element in Sorted Array

1231. Divide Chocolate

1283. Find the Smallest Divisor Given a Threshold

1482. Minimum Number of Days to Make m Bouquets

1539. Kth Missing Positive Number

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13637439.html