用 Python 编写程序,查找两个列表中两个元素之间的最小差异
pythonserver side programmingprogramming更新于 2026/2/1 19:24:17
假设我们有两个列表 L1 和 L2,我们必须找到 L1 中的数字和 L2 中的数字之间的最小差异。
因此,如果输入为 L1 = [2, 7, 4], L2 = [16, 10, 11],则输出将为 3,因为最小差异为 10 - 7 = 3。
为了解决这个问题,我们将遵循以下步骤 −
- 对列表 L1 进行排序并对列表 L2 进行排序
- ans := infinity
- i := 0, j := 0
- while i < size of L1 and j < L2 的大小,do
- ans := ans 的最小值和 |L1[i] - L2[j]|
- 如果 L1[i] < L2[j],则
- i := i + 1
- 否则,
- j := j + 1
- 返回 ans
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def solve(self, L1, L2):
L1.sort()
L2.sort()
ans = float("inf")
i = j = 0
while i < len(L1) and j < len(L2):
ans = min(ans, abs(L1[i] - L2[j]))
if L1[i] < L2[j]:
i += 1
else:
j += 1
return ans
ob = Solution()
L1 = [2, 7, 4] L2 = [16, 10, 11]
print(ob.solve(L1, L2))
输入
[2, 7, 4], [16, 10, 11]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

