乐趣区

关于javascript:获取两个有序数组的中位数

传入两个有序数组,并返回中位数

function getAllMid(arr1, arr2) {const result = [];
  let p1 = arr1.length - 1;
  let p2 = arr2.length - 1;

  while (p1 >= 0 && p2 >= 0) {arr1[p1] > arr2[p2] ? result.push(arr1[p1--]) : result.push(arr2[p2--]);
  }
  while (p1 >= 0) {result.push(arr1[p1--]);
  }
  while (p2 >= 0) {result.push(arr1[p2--]);
  }
  const p = result.length;
  if (p % 2) {return result[(p - 1) / 2];
  } else {return (result[p / 2 - 1] + result[p / 2]) / 2;
  }
}
退出移动版