题目

image.png

思路

  • 合并链表,需要一个合并方法,由因为是两两合并,因此可以通过分治法将链表拆分成两个为一组的形式

    代码

    1. public ListNode mergeKLists(ListNode[] lists) {
    2. int len = lists.length;
    3. if (len == 0) return null;
    4. if (len == 1) return lists[0];
    5. return recur(lists, 0, len - 1);
    6. }
    7. public ListNode recur(ListNode[] lists, int left, int right) {
    8. if (left == right) return lists[left];
    9. if (right - left + 1 == 2) return merge(lists[left], lists[right]);
    10. ListNode l = recur(lists, left, (left + right) / 2);
    11. ListNode r = recur(lists, (left + right) / 2 + 1, right);
    12. return merge(l, r);
    13. }
    14. public ListNode merge(ListNode p1, ListNode p2) {
    15. ListNode dummy = new ListNode(0);
    16. ListNode cur = dummy;
    17. while (p1 != null && p2 != null) {
    18. if (p1.val > p2.val) {
    19. cur.next = p2;
    20. p2 = p2.next;
    21. } else {
    22. cur.next = p1;
    23. p1 = p1.next;
    24. }
    25. cur = cur.next;
    26. }
    27. ListNode p = p1 == null ? p2 : p1;
    28. cur.next = p;
    29. return dummy.next;
    30. }

    合并K个升序链表