题解 | #归并排序-最小的K个数#
最小的K个数
http://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
function GetLeastNumbers_Solution(input, k)
{
// write code here
if(k>input.length){return [];}
let ans = merge(input);
//console.log('jj'+ans);
return ans.slice(0,k);
}
function merge(arr){
if(arr.length < 2) return arr;
let mid = Math.floor(arr.length / 2);
return mergetwo(merge(arr.slice(0,mid)),merge(arr.slice(mid)));
}
function mergetwo(arr1,arr2){
let ans = [];
let len = arr1.length + arr2.length;
for(let i = 0,j=0,index = 0;index<len;index++){
if(i>=arr1.length){
ans[index] = arr2[j++];
}else if(j>=arr2.length){
ans[index] = arr1[i++];
}else if(arr1[i]<=arr2[j]){
ans[index] = arr1[i++];
}else{
ans[index] = arr2[j++];
}
}
//console.log(ans);
return ans;
}
module.exports = {
GetLeastNumbers_Solution : GetLeastNumbers_Solution
};