题目要求合并k个升序的链表并返回,要求很简洁。
对于这个问题可以先从简单的情况入手,当我们需要合并两个升序链表怎么办?很简单对吧。
- 定义一个head节点作为合并后链表的头节点
- 定义aPre和bPre节点记录当前的a,b两个链表还没有进行合并的剩余节点中的第一个节点
- 定义tail节点记录合并链表当前的最后一个尾节点
- 对aPre和bPre的val进行比较并且把小的节点作为tail的下一节点
- 停止条件是a,b中有至少一个为空(任何一个为空后直接把另一个链表整个作为tail的下一节点)
public ListNode mergeTwo(ListNode a, ListNode b){
if(a == null || b == null) return a != null ? a : b;
ListNode head = new ListNode(0);
ListNode tail = head, aPre = a, bPre = b;
while(aPre != null && bPre != null){
if(aPre.val > bPre.val){
tail.next = bPre;
bPre = bPre.next;
}else{
tail.next = aPre;
aPre= aPre.next;
}
tail = tail.next;
}
tail.next = aPre == null ? bPre : aPre;
return head.next;
}
解决了两个链表的合并,我们可以依次类推4,8,16等等。说到这里想必能发现这个不就是分治思想的实现吗,那么问题再一次变得简单了;
正向推导的话,我们将k个链表进行配对然后对其进行合并
public ListNode merge(ListNode[] lists, int l, int r){
if(l == r) return lists[l];
if(l > r) return null;
int mid = (l + r) / 2;
return mergeTwo(merge(lists, l, mid), merge(lists, mid + 1, r));
}
OK现在所有的任务完成了,最后的Solution:
/**
* 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 mergeKLists(ListNode[] lists) {
return merge(lists, 0, lists.length - 1);
}
public ListNode merge(ListNode[] lists, int l, int r){
if(l == r) return lists[l];
if(l > r) return null;
int mid = (l + r) / 2;
return mergeTwo(merge(lists, l, mid), merge(lists, mid + 1, r));
}
public ListNode mergeTwo(ListNode a, ListNode b){
if(a == null || b == null) return a != null ? a : b;
ListNode head = new ListNode(0);
ListNode tail = head, aPre = a, bPre = b;
while(aPre != null && bPre != null){
if(aPre.val > bPre.val){
tail.next = bPre;
bPre = bPre.next;
}else{
tail.next = aPre;
aPre= aPre.next;
}
tail = tail.next;
}
tail.next = aPre == null ? bPre : aPre;
return head.next;
}
}
- 时间复杂度:O(kn×logk)
- 空间复杂度:O(logk)
虽然标签是Hard但是实际上还是很简单的,主要还是分治思想简化问题然后解决