2021年8月13日

JavaScript 将俩个有序数组合并为一个有序数组(每日一题)

作者 admin

function arrSort(arr1, arr2) {
var [i,j] = [0,0];
let newArr = [];
while(i < arr1.length || j <arr2.length) {
if (arr1[i] < arr2[j]) {
newArr.push(arr1[i]);
i++
} else if (arr1[i] > arr2[j]) {
newArr.push(arr2[j])
j++
} else {
if(arr1[i]) newArr.push(arr1[i]);
if(arr2[j]) newArr.push(arr2[j]);
i++;
j++
}
}
return newArr
}

let arrs = arrSort([2,4,6,7], [1,2,3,5,8,9,10,33,44,49]);

console.log(arrs);

打印出:[1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 33, 44, 49]