竞争性编程简单

两个数组中最接近的对

“两个数组中最接近的对”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 closest_pair_two_arrays(arr1, arr2, x),它接受两个整数排序数组 arr1arr2 以及一个目标整数 x。它应该找到并返回一个元组 (a, b) ,其中 a 来自 arr1b 来自 arr2 ,这样 (a + b)x 之间的绝对差异最小化。如果存在多个这样的对,则返回 arr1 中元素最小的对。

约束条件
  • 1 <= len(arr1), len(arr2) <= 10^5
  • arr1 and arr2 are sorted in ascending order.
  • -10^9 <= arr1[i], arr2[j], x <= 10^9

示例

Example 1
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 32)
Output
(1, 30)
Explanation

1 from arr1 and 30 from arr2 sum to 31, which is closest to 32 (absolute difference is 1).

Example 2
Input
closest_pair_two_arrays([1, 4, 5, 7], [10, 20, 30, 40], 50)
Output
(7, 40)
Explanation

7 from arr1 and 40 from arr2 sum to 47, which is closest to 50 (absolute difference is 3).

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 资源

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