竞争性编程简单

最近的一对

“最近对”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 closest_pair(arr) ,它接受未排序的整数数组 arr ,并从该数组中返回具有最小绝对差值的两个整数 (x, y) 的元组。返回的元组必须按 x <= y 进行排序。如果有多对具有相同的最小差异,则返回具有较小 x 值的一对(如果它们相同,则返回较小的 y 值)。

约束条件
  • 2 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

示例

Example 1
Input
closest_pair([4, 9, 1, 32, 13])
Output
(1, 4)
Explanation

The difference between 1 and 4 is 3, which is the minimum difference possible between any two elements in the array.

Example 2
Input
closest_pair([12, 15, 17, 20, 25])
Output
(15, 17)
Explanation

The difference between 15 and 17 is 2, which is the minimum difference possible.

Need a Hint?
考虑使用特定于搜索和排序的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。