top k

作者: 墨子柚 | 来源:发表于2020-11-20 13:58 被阅读0次

解法一

最简单的,多次循环

var smallestK = function(arr, k) {
    let tempArr = [], i = 0;
    while(k--) {
        let temp = arr[0], tempIndex = 0, len = arr.length;
        arr.forEach((item, index) => {
            if(item < temp ) {
                temp = item;
                tempIndex = index;
            }
        })
        tempArr[i] = temp;
        i++;
        arr.splice(tempIndex, 1)
    }
    return tempArr
};

解法二:
快速排序

相关文章

网友评论

      本文标题:top k

      本文链接:https://www.haomeiwen.com/subject/wipdiktx.html