Leetcode 1200. Minimum Absolute Difference

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Minimum Absolute Difference

2. Solution

解析:Version 1,先对数组排序,数字对的差值最小值一定出现在两个相邻的数字之间,遍历数组,依次计算两个相邻数字之间的差值,如果差值小于最小值,则将当前数字放入一个新的结果数组中,更新最小值,如果差值等于最小值,则将当前数字对放入到结果数组中,如果大于,则不进行任何操作。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
res = []
min_value = float('inf')
for i in range(len(arr)-1):
diff = arr[i+1] - arr[i]
if diff < min_value:
min_value = arr[i+1] - arr[i]
res = [[arr[i], arr[i+1]]]
elif diff == min_value:
res.append([arr[i], arr[i+1]])
return res

Reference

  1. https://leetcode.com/problems/minimum-absolute-difference/
如果有收获,可以请我喝杯咖啡!