合并K个排序链表
题解与注释
做法1:遍历数组
时间复杂度:O(n * k) n为最长链表的值,k为链表条数
空间复杂度:O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//用户存储每次循环中,链表的最小值
ListNode node = null;
//头指针ans
ListNode ans = new ListNode(0);
//用于遍历数组用
ListNode tail = ans;
while(true) {
int i = 0;
int index = -1;
int minVal = Integer.MAX_VALUE;
//循环取出,每条链表当前的节点
for(ListNode temp: lists) {
i++;
if(temp == null) continue;
if(minVal > temp.val) {
node = temp;
minVal = temp.val;
index = i - 1;
}
}
//如果index != -1,即还有节点未被链接起来
if(index != -1) {
//链接到ans链表
tail.next = node;
tail = tail.next;
//更新被链接的那条链表
lists[index] = lists[index].next;
}
else break;
}
return ans.next;
}
}
做法2:归并排序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0)return null;
return merge(lists, 0, lists.length - 1);
}
private ListNode merge(ListNode[] lists, int lo, int hi) {
if(lo == hi) {
return lists[lo];
}
int mid = lo + (hi - lo) / 2;
ListNode l1 = merge(lists, lo, mid);
ListNode l2 = merge(lists, mid + 1, hi);
return mergeTwoLists(l1, l2);
}
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}