剑指 Offer II 073. 狒狒吃香蕉(875. 爱吃香蕉的珂珂 )
题目:
思路:
【1】本质上的思路是采用二分查找
代码展示:
标准的二分查找的方式:
//时间6 ms击败99.29% //内存42.5 MB击败28.75% class Solution { public int minEatingSpeed(int[] piles, int h) { int low = 1; int high = 0; for (int pile : piles) { high = Math.max(high, pile); } int k = high; while (low < high) { int speed = (high - low) / 2 + low; long time = getTime(piles, speed); if (time <= h) { k = speed; high = speed; } else { low = speed + 1; } } return k; } public long getTime(int[] piles, int speed) { long time = 0; for (int pile : piles) { //这里是为了向上取整,因为(speed - 1) / speed = 0;但如果多加上一个1就会变为1 int curTime = (pile + speed - 1) / speed; time += curTime; } return time; } }
优化的写法:
//时间0 ms击败100% //内存42.2 MB击败79.9% class Solution { public int minEatingSpeed(int[] piles, int h) { int n = piles.length; long sum = 0; for (int num : piles) { sum += num; } int left = (int)(sum / h + (sum % h == 0 ? 0 : 1)); int right = (int)(sum / (h - n + 1)) + 1; while(left<right){ int mid =left+(right-left>>1); int time =0; for(int p : piles){ time += (p + mid - 1) / mid; } if(time<=h)right=mid; else left=mid+1; } return left; } }