[LeetCode]#1200. Minimum Absolute Difference

Fatboy Slim
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 from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr

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:

  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

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:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet