最小的K个数

描述:给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
语言:javascript
思路:进行升序排序后,取出数组的前K个值
升序排序:

  1. 使用JS数组的sort()方法,a>b时返回1,a出现在b之后;a<b时返回-1,a出现在b之前,否则返回0
  2. 快排算法(递归),取数组的中间元素作为参照,将数组分为左右两部分,再分用递归别对这两个数组进行排序,排好后将三个部分重新组合,返回新数组

JS的sort()方法

function GetLeastNumbers_Solution(input, k)
{
    // write code here
    if(k > input.length){
        return []
    }else{
        return input.sort(function(a,b){
            if(a > b){
                return 1;
            }else if(a < b){
                return -1;
            }else{
               return 0;
            }
        }).slice(0,k)
    }
}
module.exports = {
    GetLeastNumbers_Solution : GetLeastNumbers_Solution
};

快排算法(递归)

function GetLeastNumbers_Solution(input, k)
{
    // write code here
    const quickSort = array =>{
        const mid = Math.floor(array.length / 2);  //floor()向下取整
        const left = array.filter(item => item < array[mid]); //filter()返回一个新的数组,数组中的元素值小于array[mid]
        const right = array.filter(item => item > array[mid]);
        const leftArr = left.length ? quickSort(left) : [];
        const rightArr = right.length ? quickSort(right) : [];
        return [...leftArr,array[mid],...rightArr]; //es6合并数组的写法,es5合并数组的写法是concat(a1,a2),这两种都是浅拷贝
    }
    return k > input.length ? [] : quickSort(input).slice(0,k);
}
module.exports = {
    GetLeastNumbers_Solution : GetLeastNumbers_Solution
};