NC51 合并k个已排序的链表
描述 合并\ k k 个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。 示例1 输入: [{1,2,3},{4,5,6,7}] 复制 返回值: {1,2,3,4,5,6,7}
import java.util.* ;
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists == null){
return null ;
}
return mergelist(lists , 0 , lists.size() - 1) ;
}
public ListNode mergelist(ArrayList<ListNode> lists , int left , int right){
if(left == right){
return lists.get(left) ;
}
if(left > right){
return null ;
}
int mid = left + (right - left) / 2 ;
return merge(mergelist(lists , left , mid) , mergelist(lists , mid+1 , right) ) ;
}
public ListNode merge(ListNode l1 , ListNode l2){
if(l1 == null || l2 == null){
return l1 == null ? l2 : l1 ;
}
ListNode dummy = new ListNode(-1) ;
ListNode curt = dummy ;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
curt.next = l1 ;
l1 = l1.next ;
}else{
curt.next = l2 ;
l2 = l2.next ;
}
curt = curt.next ;
}
if(l1 != null){
curt.next = l1 ;
}
if(l2 != null){
curt.next = l2 ;
}
return dummy.next ;
}
}
|