当前位置:网站首页>力扣 875. 爱吃香蕉的珂珂
力扣 875. 爱吃香蕉的珂珂
2022-06-26 05:36:00 【SP FA】
这是一道披着二分外衣的数学题。通过这道题学会了一个关于精度方面的小技巧:
由题意可知,我们如果想算吃 p i l e s [ i ] piles[i] piles[i] 所用的时间,可以通过 ⌈ p i l e s [ i ] m i d ⌉ \lceil\frac{piles[i]}{mid}\rceil ⌈midpiles[i]⌉ 来计算,其中 m i d mid mid 是二分的时候的中值。但这样在数字很大时会涉及到精度的问题,如 p i l e s [ i ] = 1000000000 piles[i]=1000000000 piles[i]=1000000000, m i d = 999999986 mid=999999986 mid=999999986,此时使用上面的公式算出结果是 2,但实际上应该是 3 才对。
解决方法
由于 p i l e s [ i ] > 0 piles[i]>0 piles[i]>0, m i d > 0 mid>0 mid>0,于是原式子等价于 ⌊ p i l e s [ i ] + m i d − 1 m i d ⌋ \lfloor\frac{piles[i]+mid-1}{mid}\rfloor ⌊midpiles[i]+mid−1⌋,这相当于在不影响结果的情况下对 p i l e s [ i ] piles[i] piles[i] 进行了放大,数变大了结果就会变大,于是避免了精度问题。具体可以将上数代入感受一下。
关于二分的思路很好想,不多赘述。直接上代码:
class Solution {
public int minEatingSpeed(int[] piles, int h) {
Arrays.sort(piles);
if (h == piles.length) {
return piles[piles.length-1];
}
int l = 1;
int r = piles[piles.length-1];
while (l < r) {
int mid = (l + r) >> 1;
int count = 0;
for (int i=0;i<piles.length;i++) {
count += (piles[i] + mid - 1) / mid;
}
if (count > h) {
l = mid + 1;
}
else r = mid;
}
return l;
}
}
边栏推荐
猜你喜欢

Leetcode513. Find the value in the lower left corner of the tree

Recursively traverse directory structure and tree presentation

Red team scoring method statistics

uni-app吸顶固定样式

Fedora alicloud source

SDN based DDoS attack mitigation

【ARM】讯为rk3568开发板buildroot添加桌面应用
![C# 40. Byte[] to hexadecimal string](/img/3e/1b8b4e522b28eea4faca26b276a27b.png)
C# 40. Byte[] to hexadecimal string

The difference between get and post in small interview questions

Leetcode513.找出树的左下角的值
随机推荐
国务院发文,完善身份认证、电子印章等应用,加强数字政府建设
[activity recommendation] cloud native, industrial Internet, low code, Web3, metauniverse... Which is the architecture hot spot in 2022
cartographer_optimization_problem_2d
Learn cache lines and pseudo sharing of JVM slowly
Secondary bootloader about boot28 Precautions for ASM application, 28035
Feelings of virtual project failure
Daily production training report (16)
生命原来如此脆弱
Last flight
A love that never leaves
Talk 5 wireless communication
Leetcode114. 二叉树展开为链表
BOM文档
Security problems in wireless networks and modern solutions
Experience of reading the road to wealth and freedom
FindControl的源代码
Fedora alicloud source
RIA想法
uniCloud云开发获取小程序用户openid
cartographer_ backend_ constraint