我正在做一个名为“最小绝对差异”的leetcode问题,当我运行它时我的代码可以工作,但在提交中我收到错误时间限制超出
这是问题描述:
给定一个由不同整数组成的数组 arr,找到任意两个元素的绝对差值最小的所有元素对。
这是代码:
class Solution(object):
def minimumAbsDifference(self, arr):
arr.sort()
s = 1000
t = []
for i in arr:
if (abs(i - arr[(arr.index(i))-1])) < s:
s = (abs(i - arr[(arr.index(i))-1]))
for i in arr:
if (abs(arr[(arr.index(i))-1] - i)) == s:
t.append([arr[arr.index(i)-1],i])
return t
您可以在一次迭代中完成:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
result = []
if len(arr) < 2:
return
arr.sort()
min_diff = 1 + arr[-1] - arr[0]
for idx in range(1,len(arr)):
diff = arr[idx] - arr[idx-1]
if diff < min_diff:
result = []
min_diff = diff
if diff <= min_diff:
result.append([arr[idx-1], arr[idx]])
return result