最小的K个数

地址

https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/

JS解法:

  • 基于快速排序
/**
 * @param {number[]} arr
 * @param {number} k
 * @return {number[]}
 */
var getLeastNumbers = function(arr, k) {
    return quikSort(arr).splice(0, k)
};

function quikSort(arr) {

    if (arr.length <= 1) return arr;

    let target = arr.splice(0, 1)[0];
    let left = [];
    let right = [];


    arr.forEach(element => {
       element < target ?left.push(element) :right.push(element); 
    });
    return quikSort(left).concat(target, quikSort(right))
}

你可能感兴趣的:(最小的K个数)