解法一:
合并K
个升序链表,可以化为进行K-1
次两个升序链表的合并,简单粗暴,直接遍历链表数组,将两个升序链表合并后的结果继续与下一个升序链表合并,直到链表数字中无需要合并的链表。代码暂无。
解法二:
采用分治法合并,将链表数组里面的链表不断二分,二分完了再往上合并,就是不断合并已经合并的链表。这里需要注意一下链表数组为空的情况。这种方法基本就是分治法的思想。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
ListNode head = new ListNode(-1);
ListNode cur = head;
while(l1 !=null && l2 !=null){
if (l1.val <= l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = (l1 == null)?l2:l1;
return head.next;
}
public ListNode merge(ListNode[] lists, int low, int high){
if (low == high) return lists[low];
if (low > high) return null;
int mid = (low + high)/2;
return mergeTwoLists(merge(lists, low, mid), merge(lists, mid+1, high));
}
public ListNode mergeKLists(ListNode[] lists) {
return merge(lists, 0, lists.length-1);
}
}