力扣-23.合并K个升序链表
题目链接
23.合并K个升序链表
class Solution {public ListNode mergeKLists(ListNode[] lists) {if (lists.length == 0)return null;if (lists.length == 1)return lists[0];int mid = lists.length / 2;ListNode[] left = Arrays.copyOfRange(lists, 0, mid);ListNode[] right = Arrays.copyOfRange(lists, mid, lists.length);ListNode l1 = mergeKLists(left);ListNode l2 = mergeKLists(right);return mergeTwo(l1, l2);}public ListNode mergeTwo(ListNode l1, ListNode l2) {ListNode dummy = new ListNode(0);ListNode cur = dummy;while (l1 != null && l2 != null) {if (l1.val < l2.val) {ListNode temp = l1.next;l1.next = null;cur.next = l1;l1 = temp;} else {ListNode temp = l2.next;l2.next = null;cur.next = l2;l2 = temp;}cur = cur.next;}if (l1 != null) {cur.next = l1;}if (l2 != null) {cur.next = l2;}return dummy.next;}
}
小结:用递归分治的思想把两个链表的合并拓展到多个,首先把链表数组划分为左右两部分,分别递归进行合并,之后把合并完成的两个数组进行合并。