1、两个有序数组合并(产生新数组)
function combineSortedArr(arr1, arr2) {
const newArr = [];
while (arr1.length && arr2.length) {
if (arr1[0] >= arr2[0]) {
newArr.push(arr2[0]);
arr2.shift();
} else {
newArr.push(arr1[0]);
arr1.shift();
}
}
if (arr1.length) {
newArr.push(...arr1);
} else if (arr2.length) {
newArr.push(...arr2);
}
return newArr;
}
console.log(combineSortedArr([1, 2, 5, 7, 8], [3, 4, 6, 7]));
2、两个有序数组合并(返回原来某个数组)
function combineSortedArr(arr1, arr2) {
let i = 0;
while (arr2[0]) {
if (arr2[0] < arr1[i]) {
arr1.splice(i, 0, arr2[0]);
arr2.shift();
} else if (arr2[0] >= arr1[arr1.length - 1]) {
arr1.push(...arr2);
arr2 = [];
} else {
i++;
}
}
return arr1;
}
console.log(combineSortedArr([1, 2, 5, 6, 7], [1, 2, 3, 4, 9]));```
网友评论