Leetcode23--->Merge K sorted Lists(合并k个排序的单链表)

时间:2023-03-09 01:40:28
Leetcode23--->Merge K sorted Lists(合并k个排序的单链表)

题目: 合并k个排序将k个已排序的链表合并为一个排好序的链表,并分析其时间复杂度 。

解题思路: 类似于归并排序的思想,lists中存放的是多个单链表,将lists的头和尾两个链表合并,放在头,头向后移动,尾向前移动,继续合并,直到头和尾相等,此时已经归并了一半, 然后以同样的方法又重新开始归并剩下的一半。时间复杂度是O(logn),合并两个链表的时间复杂度是O(n),则总的时间复杂度大概是O(nlogn);合并两个单链表算法可以参考Leetcode21中的解法:http://www.cnblogs.com/leavescy/p/5879625.html
代码如下:
 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null|| lists.length == 0)
return null;
if(lists.length == 1)
return lists[0];
int end = lists.length - 1;
int begin = 0;
while(end > 0) // 将lists的头和尾进行归并,然后将结果存放在头,头向后移动,尾向前移动,直到begin=end,则已经归并了一半,此时将begin=0,继续归并
{
begin = 0;
while(begin < end)
{
lists[begin] = combineTwoList(lists[begin], lists[end]);
begin ++;
end --;
}
} return lists[0];
}
public ListNode combineTwoList(ListNode head1, ListNode head2) // head1和head2为头节点的两个单链表的合并
{
if(head1 == null && head2 == null) // 如果两个单链表都不存在,则返回null
return null;
if(head1 == null) // 如果head1不存在,则直接返回head2
return head2;
if(head2 == null)
return head1;
ListNode pHead = null;
if(head1.val > head2.val) // 根据head1与head2的值,决定头节点
{
pHead = head2;
pHead.next = combineTwoList(head1, head2.next);
}
else
{
pHead = head1;
pHead.next = combineTwoList(head1.next, head2);
}
return pHead;
}
}