leetcode 23. 合并K个排序链表 JAVA

时间:2022-12-09 11:02:34

题目:

合并 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

解题思路:

使用归并将链表两两合并

/**
* 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 == 1 )
return lists[0];
else if(lists == null)
return null;
return MSort(lists,0,lists.length - 1);
} public ListNode MSort(ListNode[] lists, int low, int high){
if(low < high){
int mid = (low+high)/2;
ListNode leftlist = MSort(lists,low,mid);
ListNode rightlist = MSort(lists,mid+1,high);
return mergeTwoLists(leftlist,rightlist);
}
else if(low == high)
{
return lists[low];//
}
else
return null; //
} public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cur = head;
ListNode p = l1, q = l2;
while(p != null && q != null)
{
if(p.val <= q.val)
{
cur.next = new ListNode(p.val);
cur = cur.next;
p = p.next;
}
else
{
cur.next = new ListNode(q.val);
cur = cur.next;
q = q.next;
}
}
while(p != null)
{
cur.next = new ListNode(p.val);
cur = cur.next;
p = p.next;
}
while(q != null)
{
cur.next = new ListNode(q.val);
cur = cur.next;
q = q.next;
}
return head.next;
} }