鍍金池/ 問答/HTML/ js數(shù)組操作問題

js數(shù)組操作問題

給定一個(gè)有序不重復(fù)數(shù)組arr1 = [a1,a2,....,an] , 一個(gè)該數(shù)組的子集 arr2 = [b1,b2,....,bn](順序與arr1 一致)
任意給定一個(gè)arr1的元素 ai , 請將其插入 arr2 并保證 順序與 arr1 的順序一致

比如 arr1 [3,5,4,8] , arr2 [5,8] 現(xiàn)在要把 4 插入到 arr2
需要結(jié)果為 [5, 4, 8]

求一個(gè)優(yōu)雅的運(yùn)算方法

---------------分割線-------------

我采納了 @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);
}

回答
編輯回答
懶豬

嘗試下面代碼

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);
}
2017年1月9日 02:54
編輯回答
舊城人

既然是有序的……其實(shí)有沒有arr1都無所謂的……

有序的,你直接用二分把aiarr2里面塞就行了。

2018年8月18日 01:01
編輯回答
雅痞

還是二分 修改一下比較的方式就行

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)
    }
}
2017年9月15日 17:47
編輯回答
笨小蛋
  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)
2017年2月19日 17:05