我正在 LeetCode 上练习一些基于二分搜索的问题。我正在研究问题 1283(找到最小除数)。我的 python 代码每次都给出错误的答案。我决定使用本地调试器来查看哪里出错了,但出乎意料的是,我的本地调试器为相同的代码给出了正确的答案。我联系了一位已经在 CPP 中完成此题的朋友,并要求他从他的帐户运行我的代码,我的解决方案在 LeetCode 上被他的帐户接受。在发布这个问题时,我又看了一遍这个问题,发现在将第10行
s += math.ceil(i/mid)
更改为s += -(-i//mid)
时(据我所知两者具有相同的含义),LeetCode从我的帐户本身接受了我的解决方案。有谁知道这是什么原因。我真的很好奇这个。
这是我的代码
import math
class Solution(object):
def smallestDivisor(self, nums, threshold):
l,r = 1,max(nums)
div = float('inf')
while l <= r:
mid = (l+r)//2
s = 0
for i in nums:
s += math.ceil(i/mid)
if s <= threshold:
div = mid
r = mid - 1
else: l = mid + 1
return div
我将最后一行更改为
print(div)
以在本地调试器中运行。