leetcode 23. 合并K个排序链表
题意
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
解题思路
先定义mergeTwoLists
函数,该函数使用归并排序对 lists1 和 lists2 两个链表进行排序,得到一个新的链表 lists3 。对 lists 中的链表进行两两排序,最终得到一个排好序的链表。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int num = lists.length;
if (num == 0)
{
return null;
}
while (num > 1)
{
int k = (num + 1) / 2;
for (int i = 0; i < num / 2; i++)
{
lists[i] = mergeTwoLists(lists[i], lists[i + k]);
}
num = k;
}
return lists[0];
}
private ListNode mergeTwoLists(ListNode lists1, ListNode lists2)
{
ListNode lists3 = new ListNode(0);
ListNode cur = lists3;
ListNode l1 = lists1;
ListNode l2 = lists2;
while (l1 != null || l2 != null)
{
if (l1 == null)
{
ListNode nextNode = new ListNode(l2.val);
cur.next = nextNode;
cur = cur.next;
l2 = l2.next;
continue;
}
if (l2 == null)
{
ListNode nextNode = new ListNode(l1.val);
cur.next = nextNode;
cur = cur.next;
l1 = l1.next;
continue;
}
if (l1.val < l2.val)
{
ListNode nextNode = new ListNode(l1.val);
cur.next = nextNode;
cur = cur.next;
l1 = l1.next;
}
else
{
ListNode nextNode = new ListNode(l2.val);
cur.next = nextNode;
cur = cur.next;
l2 = l2.next;
}
}
lists3 = lists3.next;
return lists3;
}
}