[路飞]_今夜合链表

577 阅读1分钟

「这是我参与11月更文挑战的第12天,活动详情查看:2021最后一次更文挑战21. 合并两个有序链表
合并K个升序链表

合并两个有序链表

递归合并

看演示

幻灯片1.gif

幻灯片2.gif

幻灯片3.gif

幻灯片4.gif

幻灯片5.gif

幻灯片6.gif

根据上述演示编辑代码如下:

var mergeTwoLists = function (l1, l2) {
  if (l1 == null) return l2
  if (l2 == null) return l1
  if (l1.val < l2.val) {
    l1.next = mergeTwoLists(l1.next, l2)
    return l1
  } else {
    l2.next = mergeTwoLists(l1, l2.next)
    return l2
  }
}

合并K个升序链表

经过上一题,合并两个有序链表,再合并K个升序链表理解起来就比较简单了;

将数组中的链表前两个合并成为新数组,新链表再与下一链表合并;直到合并到数组中最后一位链表;完成

迭代法


var mergeKLists = function (lists) {
  const len = lists.length
  if (len === 0) return null
  if (len === 1) return lists[0]
  let start = lists[0]
  for (let i = 1; i < len; i++) {
    const curr = lists[i]
    start = mergeTwoListNode(start, curr)
  }
  return start

  function mergeTwoListNode(l1, l2) {
    if (l1 === null) return l2
    if (l2 == null) return l1
    if (l1.val < l2.val) {
      l1.next = mergeTwoListNode(l1.next, l2)
      return l1
    } else {
      l2.next = mergeTwoListNode(l1, l2.next)
      return l2
    }
  }
}

时间复杂度:O(n*k^2)

递归法

递归发


var mergeKLists = function (lists) {
  return loop(lists)
  function loop(lists) {
    const len = lists.length
    if (len === 0) return null
    if (len === 1) return lists[0]
    const m = len >> 1 // len/2 向下去整
    let temp = []
    for (let i = 0; i < m; i++) {
      temp.push(mergeTwoListNode(lists[2 * i], lists[2 * i + 1]))
    }
    if (len % 2 === 1) {
      temp.push(lists[len - 1])
    }
    return loop(temp)
  }

  function mergeTwoListNode(l1, l2) {
    if (l1 === null) return l2
    if (l2 == null) return l1
    if (l1.val < l2.val) {
      l1.next = mergeTwoListNode(l1.next, l2)
      return l1
    } else {
      l2.next = mergeTwoListNode(l1, l2.next)
      return l2
    }
  }
}

时间复杂度为:O(kn*logk)