<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
pre {
font-size: 20px;
}
</style>
</head>
<body>
<pre>
给出两个有升序数组,实现函数 combine(arr1,arr2),
使返回结果仍然有序
如: combine([1,2,3],[2,4,5,6]) 输出 [1,2,2,3,4,5,6]
</pre>
<script>
/*
给出两个升序数组,实现函数 combine(arr1,arr2),
使返回结果仍然有序
如: combine([1,2,3],[2,4,5,6]) 输出 [1,2,2,3,4,5,6]
*/
const combine = (arr1, arr2) => {
let res = [];
while (arr1.length > 0 || arr2.length > 0) {
if (arr1[0] > arr2[0]) {
res.push(arr2.shift());
} else {
res.push(arr1.shift());
}
if (arr2.length === 0) {
res = res.concat(arr1);
arr1 = [];
continue;
}
if (arr1.length === 0) {
res = res.concat(arr2);
arr2 = [];
continue;
}
}
return res;
}
console.log(combine([1, 2, 3], [2, 3, 4]));
</script>
</body>
</html>
JavaScript合并升序数组
猜你喜欢
转载自blog.csdn.net/qq_33807889/article/details/105149645
今日推荐
周排行