用js刷剑指offer(最小的K个数)

时间:2023-03-09 04:51:16
用js刷剑指offer(最小的K个数)

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
牛客网链接

js代码

function GetLeastNumbers_Solution(input, k)
{
// write code here
const res = []
if (input.length === 0) return res
if (k > input.length) return res
let temp
for (let i = 0; i < k; i++) {
for (let j = 0; j < input.length-i-1; j++) {
if (input[j] < input[j+1]) {
temp = input[j+1]
input[j+1] = input[j]
input[j] = temp
}
}
res.push(input[input.length-1-i])
}
return res
}