4 回答
TA贡献1810条经验 获得超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);
}
TA贡献1793条经验 获得超6个赞
还是二分 修改一下比较的方式就行
let arr1 = [3,5,4,8]
let arr2 = [5,8]
let indexMap = {}
for(let i=0;i<arr1.length;i++){
indexMap[arr1[i]] = i
}
insert(arr2,0,arr2.length,4)
console.log(JSON.stringify(arr2))
function insert(arr,l,r,num){
if(l==r){
arr.splice(l, 0, num)
return
}
let index = parseInt((r+l)/2)
if(indexMap[arr[index]]<indexMap[num]){
insert(arr,index+1,r,num)
}else{
insert(arr,l,index,num)
}
}
TA贡献2065条经验 获得超13个赞
let source = [3, 5, 4, 8]
let target = [5, 8]
let insert = 4
let index = source.indexOf(insert)
for (let i = 0; i < target.length; i++) {
let source_index = source.indexOf(target[i])
if (source_index > index) {
target.splice(i, 0, insert)
break
}
}
if (target.indexOf(insert) === -1) target.push(insert)
添加回答
举报