LeetCode: Find K Closest Elements Solution
Sort with custom comparatorApproach
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[]} arr3 * @param {number} k4 * @param {number} x5 * @return {number[]}6 */7var findClosestElements = function (arr, k, x) {8 return arr.sort(compareFunction(x)).slice(0, k).sort(compareFunctionGt)9}1011const 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 : 014}1516const compareFunctionGt = (a, b) => a - b
References
Comments
Loading comments...
Tags
leetcode
array
sorting
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
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