[LeetCode]#1200. Minimum Absolute Difference

  • a, b are from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr
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.
  1. Sort arr.
  2. st=abs(arr[1]-arr[0])
  3. if st == abs(arr[i]-arr[i-1]), add to and[arr[i-1],arr[i]]
  4. if st > abs(arr[i]-arr[i-1]), replace new st and ans.
  5. Return ans
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store