-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathminimumAbsDifference.js
More file actions
51 lines (34 loc) · 1.29 KB
/
minimumAbsDifference.js
File metadata and controls
51 lines (34 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
https://leetcode.com/problems/minimum-absolute-difference/
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.
* @param {number[]} arr
* @return {number[][]}
*/
var minimumAbsDifference = function(arr) {
if (!arr) return arr;
if (arr.length < 2) return arr;
let sortedArr = arr.sort((a,b) => a-b);
let minDiff = function () {
let minValue = Infinity;
for (let i = 0; i < sortedArr.length - 1; i++) {
minValue = Math.min(minValue, sortedArr[i+1] - sortedArr[i]);
}
return minValue;
}();
let result = [];
for (let i = 0; i < sortedArr.length - 1; i++) {
if ((sortedArr[i+1] - sortedArr[i]) === minDiff) {
result.push([sortedArr[i], sortedArr[i+1]]);
}
}
console.log(result)
return result;
};