js数组操作问题

给定一个有序不重复数组arr1 = [a1,a2,....,an] , 一个该数组的子集 arr2 = [b1,b2,....,bn](顺序与arr1 一致)

任意给定一个arr1的元素 ai , 请将其插入 arr2 并保证 顺序与 arr1 的顺序一致


比如 arr1 [3,5,4,8] , arr2 [5,8] 现在要把 4 插入到 arr2

需要结果为 [5, 4, 8]


求一个优雅的运算方法


---------------分割线-------------


我采纳了 @hkuclion 的答案 并作了小小的修改


let source = [3,5,4,8];

let target = [5,8];

let needle = 4;


let source_index = source.indexOf(needle);

if(source_index !== -1){

    let target_index = -1;

    while (source_index && target_index === -1) {

        target_index = target.indexOf(source[--source_index]);

    }

    target.splice(target_index + 1, 0, needle);

}


收到一只叮咚
浏览 449回答 4
4回答

慕莱坞森

尝试下面代码let source = [3,5,4,8];let target = [5,8];let needle = 4;let source_index = source.indexOf(needle);if(source_index !== -1){    let target_index = source_index? target.indexOf(source[source_index - 1]) + 1:source_index;    target.splice(target_index, 0, needle);}

摇曳的蔷薇

还是二分 修改一下比较的方式就行let arr1 = [3,5,4,8]&nbsp;let arr2 = [5,8]&nbsp;let indexMap = {}for(let i=0;i<arr1.length;i++){&nbsp; &nbsp; indexMap[arr1[i]] = i}insert(arr2,0,arr2.length,4)console.log(JSON.stringify(arr2))function insert(arr,l,r,num){&nbsp; &nbsp; if(l==r){&nbsp; &nbsp; &nbsp; &nbsp; arr.splice(l, 0, num)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; let index = parseInt((r+l)/2)&nbsp; &nbsp; if(indexMap[arr[index]]<indexMap[num]){&nbsp; &nbsp; &nbsp; &nbsp; insert(arr,index+1,r,num)&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; insert(arr,l,index,num)&nbsp; &nbsp; }}

翻翻过去那场雪

&nbsp; let source = [3, 5, 4, 8]&nbsp; let target = [5, 8]&nbsp; let insert = 4&nbsp; let index = source.indexOf(insert)&nbsp; for (let i = 0; i < target.length; i++) {&nbsp; &nbsp; let source_index = source.indexOf(target[i])&nbsp; &nbsp; if (source_index > index) {&nbsp; &nbsp; &nbsp; target.splice(i, 0, insert)&nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }&nbsp; }&nbsp; if (target.indexOf(insert) === -1) target.push(insert)

德玛西亚99

既然是有序的……其实有没有arr1都无所谓的……有序的,你直接用二分把ai往arr2里面塞就行了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript