Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 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) {
ListNode temp = new ListNode(0);
ListNode result = temp;
int time = 0;
int length = 0;//第一次遍历判断所有链表节点长度
for (int i = 0;i<lists.length;i++){
ListNode x = lists[i];
while(x != null){
x = x.next;
length++;
}
}
int num = 0;
for(int i =0;i<length;i++){
ListNode temp1 = new ListNode(10000);
for(int j = 0 ; j < lists.length ; j++){
if(lists[j] == null)
continue;
if(temp1.val>lists[j].val){
temp1.val = lists[j].val;
time = j;
}
}
temp.next = temp1;
temp = temp.next;
if(lists[time] != null)
lists[time] = lists[time].next;
}
return result.next;
}
}
结果果然很差劲。
修改代码,改变实现方式,使用归并排序
网上大神的一个代码,总体思路就是归并排序,使用递归,最后变成两个链表的合并操作。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//divide and conquer
//time: o(nlogk) n:the number of nodes of k lists
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0) return null;
return helper(lists, 0, lists.length - 1);
}
public ListNode helper(ListNode[] lists, int start, int end){
if(start == end){
return lists[start];
}
int mid = (end - start) / 2 + start;
ListNode left = helper(lists, start, mid);
ListNode right = helper(lists, mid + 1, end);
return mergeTwoLists(left, right);
}
public ListNode mergeTwoLists(ListNode left, ListNode right){
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
while(left != null && right != null){
if(left.val <= right.val){
tail.next = new ListNode(left.val);
left = left.next;
tail = tail.next;
}else{
tail.next = new ListNode(right.val);
right = right.next;
tail = tail.next;
}
}
if(left != null){
tail.next = left;
}
if(right != null){
tail.next = right;
}
return dummy.next;
}
}