[LeetCode]#1200. Minimum Absolute Difference
1 min readJan 29, 2021
Environment: Python 3.8
Key technique: if, append
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b]
follows
a, b
are fromarr
a < b
b - a
equals to the minimum absolute difference of any two elements inarr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Analysis:
- Sort arr.
- st=abs(arr[1]-arr[0])
- if st == abs(arr[i]-arr[i-1]), add to and[arr[i-1],arr[i]]
- if st > abs(arr[i]-arr[i-1]), replace new st and ans.
- Return ans
Solution:
class Solution:
def minimumAbsDifference(self, arr):
ans=[]
arr.sort()
st=abs(arr[1]-arr[0])
for i in range(1,len(arr)):
if (abs(arr[i]-arr[i-1]))==st:
ans.append([arr[i-1],arr[i]])
elif arr[i]-arr[i-1] < st:
ans=[[arr[i-1],arr[i]]]
st =arr[i]-arr[i-1]
return ans
Submissions: