复习一下这道题。我一直都是用merge sort解法做的。今天在搜索别的解法时,发现这个文章讲的非常好: http://bangbingsyb.blogspot.com/2014/11/leetcode-merge-k-sorted-lists.html. 我的解法应该是属于第三种, time complexity nklog(k)
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
return MSort(lists, 0, lists.length - 1);
}
public ListNode MSort(ListNode[] lists, int start, int end) {
if (start < end) {
int mid = start + (end - start) / 2;
ListNode left = MSort(lists, start, mid);
ListNode right = MSort(lists, mid + 1, end);
return mergeTwoLists(left, right);
}
return lists[start];
}
public ListNode mergeTwoLists(ListNode left, ListNode right) {
if (left == null && right == null) {
return null;
} else if (left == null) {
return right;
} else if (right == null) {
return left;
}
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (left != null && right != null) {
if (left.val > right.val) {
head.next = right;
right = right.next;
} else {
head.next = left;
left = left.next;
}
head = head.next;
}
if (left != null) {
head.next = left;
} else if (right != null) {
head.next = right;
}
return dummy.next;
}
}