LeeCode:Day1-两个有序数组合并成一个有序数组

482 阅读1分钟

思路:取出两个数组的小端拿出来比较,将更小者放入结果数组。当一个数组放完,将另一个数组的剩余依次放入结果数组即可。

代码:

function combineTwoSortedArray(a, b) {
  const result = []
  let Rindex = 0
  let Aindex = 0
  let Bindex = 0
  while (Aindex < a.length && Bindex < b.length) {
    if (a[Aindex] <= b[Bindex]) {
      result[Rindex] = a[Aindex]
      Aindex++
    } else {
      result[Rindex] = b[Bindex]
      Bindex++
    }
    Rindex++
  }
  while (Aindex < a.length) {
    result[Rindex] = a[Aindex]
    Rindex++
    Aindex++
  }
  while (Bindex < b.length) {
    result[Rindex] = b[Bindex]
    Rindex++
    Bindex++
  }
  return result
}
const a = [1, 3, 5, 6, 7],
  b = [2, 3, 9]
const result = combineTwoSortedArray(a, b)
console.log(result)