LeetCode: Find K Closest Elements Solution

Sort with custom comparator

Approach

From MDN Web Doc for Array.prototype.sort():

If compareFunction(a, b) returns a value > than 0, sort b before a

Steps:

  • Sort the array by the main criteria
  • Get first k elements
  • Sort ascending

Implementation

1/**
2 * @param {number[]} arr
3 * @param {number} k
4 * @param {number} x
5 * @return {number[]}
6 */
7var findClosestElements = function (arr, k, x) {
8 return arr.sort(compareFunction(x)).slice(0, k).sort(compareFunctionGt)
9}
10
11const compareFunction = x => (a, b) => {
12 const [absAx, absBx] = [Math.abs(a - x), Math.abs(b - x)]
13 return absAx < absBx || (absAx === absBx && a < b) ? -1 : 0
14}
15
16const compareFunctionGt = (a, b) => a - b

References

Array.prototype.sort() (MDN Web Docs)

Comments

Loading comments...

Tags

leetcode

array

sorting

Next Post

LeetCode: Count Vowels Permutation

Memoized recursion

Previous Post

Toptal Interview Process Guide and Review

Journey of a non-native English-speaker developer on looking for a remote opportunity

HoningJS

Search Posts