Python程序:查找两对数字,使其和的差最小
假设我们有一个名为 nums 的数字列表,我们希望从中选择两对数字,使得这两对数字的和的绝对差最小。
因此,如果输入类似于 nums = [3, 4, 5, 10, 7],则输出将为 1,因为我们可以选择这些对 (3 + 7) - (4 + 5) = 1。
为了解决这个问题,我们将遵循以下步骤
- distances := 新列表
- 对于 i 从 0 到 nums 大小 - 2,执行
- 对于 j 从 i + 1 到 nums 大小 - 1,执行
- 在 distances 的末尾插入列表 [|nums[i] - nums[j]| , i, j]
- 对列表 distances 进行排序
- ans := 1^9
- 对于 i 从 0 到 distances 大小 - 2,执行
- [dist, i1, i2] := distances[i]
- j := i + 1
- [dist2, i3, i4] := distances[j]
- 当 j < distances 大小 且 (i1, i2, i3, i4) 中的元素不唯一时,执行
- [dist2, i3, i4] := distances[j]
- j := j + 1
- 如果 (i1, i2, i3, i4) 中的元素唯一,则
- ans := ans 和 (dist2 - dist) 的最小值
- 返回 ans
- 对于 j 从 i + 1 到 nums 大小 - 1,执行
让我们看看以下实现,以便更好地理解
示例代码
class Solution: def solve(self, nums): distances = [] for i in range(len(nums) - 1): for j in range(i + 1, len(nums)): distances.append((abs(nums[i] - nums[j]), i, j)) distances.sort() ans = 1e9 for i in range(len(distances) - 1): dist, i1, i2 = distances[i] j = i + 1 dist2, i3, i4 = distances[j] while j < len(distances) and len({i1, i2, i3, i4}) != 4: dist2, i3, i4 = distances[j] j += 1 if len({i1, i2, i3, i4}) == 4: ans = min(ans, dist2 - dist) return ans ob = Solution() nums = [3, 4, 5, 10, 7] print(ob.solve(nums))
输入
[3, 4, 5, 10, 7]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
1
广告