Original link: leetcode-cn.com/problems/zu…

Answer:

  1. Sort the array from smallest to largest.
  2. Iterates through the sorted array, fetching the first k elements.
/ * * *@param {number[]} arr
 * @param {number} k
 * @return {number[]}* /
var getLeastNumbers = function(arr, k) {
  let result = []; // Store the result
  arr.sort((a, b) = > a - b); // Sort the array from smallest to largest

  // Retrieves k elements from sorted array
  for (let i = 0; i < k; i++) {
    result.push(arr[i]);
  }
  
  return result;
};
Copy the code
/ * * *@param {number[]} arr
 * @param {number} k
 * @return {number[]}* /
var getLeastNumbers = function(arr, k) {
  return arr.sort((a, b) = > a - b).splice(0, k)
};
Copy the code