Time Cost

20min38s

Implementation

The solution’s time complexity is n*log(n). Some boundaries should be noticed such as “hour_needed” could be over maximum integer.

Code

  • My Solution
    class Solution {
    public:
      int minEatingSpeed(vector<int>& piles, int h) {
          // n*logn
          int base = 1, ceil = 0;
          for (int pile: piles) {
              ceil = max(ceil, pile);
          }
    
          int bisec = (base + ceil) / 2;
          long hour_needed = 0;
          int result = INT_MAX;
          double a = 0.0;
          int b = 0;
          while (base <= ceil) {
              for (int pile: piles) {
                  a = static_cast<double>(pile) / static_cast<double>(bisec);
                  b = static_cast<int>(std::ceil(a));
                  hour_needed += b;
              }
              if (hour_needed <= h) {
                  result = min(result, bisec);
                  ceil = bisec - 1;
                  bisec = (base + ceil) / 2;
              }else{
                  base = bisec + 1;
                  bisec = (base + ceil) / 2;
              }
              hour_needed = 0;
          }
          return result;
      }
    };