题目描述:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路解析:
- 归并排序是排列数组的,现在应用到排列list
这里来复习一下Merge Sort(对于数组操作),参考Wikipedia:
归并操作(merge),也叫归并算法,指的是将两个已经排序的序列合并成一个序列的操作。归并排序算法依赖归并操作。
归并操作的过程如下:
- 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
- 设定两个指针,最初位置分别为两个已经排序序列的起始位置
- 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
- 重复步骤3直到某一指针到达序列尾
- 将另一序列剩下的所有元素直接复制到合并序列尾
参考:https://www.cnblogs.com/springfor/p/3869217.html
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists==null || lists.size()==0)
return null;
return Msort(lists,0,lists.size()-1);
}
public ListNode Msort(ArrayList<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);
}
return lists.get(low);
}
public ListNode MergeTwoLists(ListNode l1,ListNode l2){
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode l3;
ListNode fakehead = new ListNode(-1);
if(l1.val<l2.val){
l3=l1;
l1=l1.next;
}
else{
l3 =l2;
l2=l2.next;
}
fakehead.next=l3;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
l3.next = l1;
l3 = l3.next;
l1 = l1.next;
}else{
l3.next = l2;
l3=l3.next;
l2=l2.next;
}
}
if(l1!=null){
l3.next = l1;
}
if(l2!=null){
l3.next = l2;
}
return fakehead.next;
}
}