合并两个有序数组

  改变原数组

function merge(arr1 = [2,3,4,5,7],arr2 = [3,5,6,7,9,10]){
    let res = []
    while(arr1.length && arr2.length){
        if(arr1[0] > arr2[0]){
            res.push(arr2.shift())
        }else if(arr1[0] < arr2[0]){
            res.push(arr1.shift())
        }else{
            res.push(arr1.shift())
            res.push(arr2.shift())
        }
    }
    let _arr = arr1.length ? arr1 :arr2
    res.push(..._arr)
    return res
}

  不改变原数组

const merge = (arr1 = [2, 3, 4, 5, 7], arr2 = [3, 5, 6, 7, 9, 10]) => {
    const res = []
    let i = 0,
        j = 0
    while (i < arr1.length && j < arr2.length) {
        if (arr1[i] < arr2[j]) {
            res.push(arr1[i])
            i++
        } else if (arr1[i] > arr2[j]) {
            res.push(arr2[j])
            j++
        } else {
            res.push(arr1[i])
            i++
            res.push(arr2[j])
            j++
        }
    }
    const _arr = arr1.slice(i).concat(arr2.slice(j))
    return res.concat(_arr)
}

  

posted @ 2020-08-26 18:22  671_MrSix  阅读(201)  评论(0编辑  收藏  举报