0023. Merge k Sorted Lists (H)

Merge k Sorted Lists (H)

题目

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

题意

将k个有序链表合并为一个有序链表。

思路

与二路归并类似的方法,但可以利用优先队列来找k个结点中的最小结点。

也可以将所有链表分为若干个小组,每次都进行二路归并,最后归并成一个大链表。

两种方法的时间复杂度都为\(O(Nlogk)\),但实际提交后运行时间相差较大,分析原因可能在于:优先队列法中,每一个结点都需要单独连接到新链表后,而分治法中,当两个链表中其中一个为null时,可以将另一个链表中剩余的结点直接连接到新链表后,省去了一部分时间。


代码实现

Java

优先队列

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        Queue q = new PriorityQueue<>((x, y) -> x.val - y.val);
        for (ListNode head : lists) {
            if (head != null) {
                q.offer(head);
            }
        }
        while (!q.isEmpty()) {
            cur.next = q.poll();
            cur = cur.next;
            if (cur.next != null) {
                q.offer(cur.next);
            }
        }
        return dummy.next;
    }
}

分治法

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        // 特殊情况先排除,不然数组下标会溢出
        if (lists.length == 0) {
            return null;
        }
        for (int step = 1; step < lists.length; step *= 2) {
            for (int i = 0; i + step < lists.length; i += 2 * step) {
                lists[i] = mergeTwo(lists[i], lists[i + step]);
            }
        }
        return lists[0];
    }

    private ListNode mergeTwo(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode pointer = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                pointer.next = l1;
                l1 = l1.next;
            } else {
                pointer.next = l2;
                l2 = l2.next;
            }
            pointer = pointer.next;
        }
        pointer.next = l1 == null ? l2 : l1;
        return head.next;
    }
}

JavaScript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
  if (lists.length === 0) {
    return null
  }

  for (let step = 1; step < lists.length; step *= 2) {
    for (let i = 0; i + step < lists.length; i += step * 2) {
      lists[i] = merge(lists[i], lists[i + step])
    }
  }
  return lists[0]
}

let merge = function (list1, list2) {
  let dummy = new ListNode()
  let cur = dummy
  while (list1 !== null && list2 !== null) {
    if (list1.val < list2.val) {
      cur.next = list1
      list1 = list1.next
    } else {
      cur.next = list2
      list2 = list2.next
    }
    cur = cur.next
  }
  cur.next = list1 ? list1 : list2
  return dummy.next
}

你可能感兴趣的:(0023. Merge k Sorted Lists (H))