1 import sys 2 class Solution: 3 def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: 4 n = len(arr) 5 arr = sorted(arr) 6 if n == 2: 7 return [arr] 8 dic = {} 9 minval = sys.maxsize 10 for i in range(n-1): 11 j = i + 1 12 diff = arr[j] - arr[i] 13 if diff <= minval: 14 minval = diff 15 if diff not in dic: 16 dic[diff] = [[arr[i],arr[j]]] 17 else: 18 dic[diff].append([arr[i],arr[j]]) 19 20 return dic[minval]
先将数据排序,然后计算相邻数组的差值,使用字典保存最小差值所包含的元素对。