问题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
分析:
这个题在困难里面算比较简单的吧。用二分法,两个两个合并,复杂度就是
代码:
/**
* 合并 K 个排序链表
* Merge k Sorted Lists
*
* @author DongWei
* @version 2019/12/20
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
return mergeLists(lists, 0, lists.length - 1);
}
/*
二分法,把列表分为两个部分归并,再归并最后的结果
*/
private ListNode mergeLists(ListNode[] lists, int left, int right) {
if (left > right) {
return null;
}
if (left == right) {
return lists[left];
}
int mid = (left + right) >>> 1;
ListNode leftList = mergeLists(lists, left, mid);
ListNode rightList = mergeLists(lists, mid + 1, right);
return merge(leftList, rightList);
}
/*
归并两个链表
*/
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
int val1 = l1.val;
int val2 = l2.val;
if (val1 < val2) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if (l1 != null) {
cur.next = l1;
} else {
cur.next = l2;
}
return dummy.next;
}
}
运行速度2ms~3ms