题目:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思考:
因为数组的长度不定,所以其实当我们合并的时候,最多也只能合并两个子链表;
由此想到,此题可以用二分法来接,分别合并,最后得到大的结果;
合并两个链表按照升序排列教简单,直接用指针做就可以,移动到最后位置即可;
注意边界条件。
MARK!执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
代码:
// 合并k个升序列表
public static ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
return mergetList(lists, 0, lists.length - 1);
}
public static ListNode mergetList(ListNode[] lists, int start, int end) {
if (start == end) {
return lists[start];
} else {
int middle = (start + end) / 2;
return mergetTwoList(mergetList(lists, start, middle), mergetList(lists, middle + 1, end));
}
}
public static ListNode mergetTwoList(ListNode a, ListNode b) {
ListNode m = a;
ListNode n = b;
ListNode newNode = null;
ListNode begin = null;
while (m != null && n != null) {
if (m.val < n.val) {
if (newNode == null) {
newNode = m;
begin = a;
} else {
newNode.next = m;
newNode = newNode.next;
}
m = m.next;
} else {
if (newNode == null) {
newNode = n;
begin = b;
} else {
newNode.next = n;
newNode = newNode.next;
}
n = n.next;
}
}
if (m != null) {
if (newNode == null) {
newNode = m;
begin = a;
} else {
newNode.next = m;
}
}
if (n != null) {
if (newNode == null) {
newNode = n;
begin = b;
} else {
newNode.next = n;
}
}
return begin;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}