Description
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
Mind path
多个有序node如果一次取一个需要循环一遍,这样每个都需要重复比较很多遍,借鉴mergeSort,将list分成两部分分别merge,递归merge一次只merge两个node,可以大大减少元素的比较次数。
由于每个元素需要比较log(k)次,所以时间复杂度应该是(size-of-all-elements)*log(n)
Solution
package com.dylan.leetcode;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by liufengquan on 2018/8/1.
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
if (lists.length == 1) {
return lists[0];
}
return merge(lists, 0, lists.length);
}
private ListNode merge(ListNode[] nodes, int left, int right) {
if ((right - left) == 1) {
return nodes[left];
}
if ((right - left) == 2) {
//merge
return merge(nodes[left], nodes[left + 1]);
}
int middle = left + (right - left) / 2;
return merge(merge(nodes, left, middle), merge(nodes, middle, right));
}
private ListNode merge(ListNode node1, ListNode node2) {
ListNode temp = new ListNode(0);
ListNode head = temp;
while (node1 != null && node2 != null) {
if (node1.val > node2.val) {
temp.next = node2;
temp = temp.next;
node2 = node2.next;
}else {
temp.next = node1;
temp = temp.next;
node1 = node1.next;
}
}
if (node1 != null) {
temp.next = node1;
}
if (node2 != null) {
temp.next = node2;
}
return head.next;
}
@Test
public void test() {
ListNode node1 = new ListNode(1);
node1.next = new ListNode(4);
node1.next.next = new ListNode(5);
ListNode node2 = new ListNode(1);
node2.next = new ListNode(3);
node2.next.next = new ListNode(4);
ListNode node3 = new ListNode(2);
node3.next = new ListNode(6);
ListNode[] nodes = new ListNode[]{node1, node2, node3};
ListNode result = mergeKLists(nodes);
Assert.assertEquals(1, result.val);
result = result.next;
Assert.assertEquals(1, result.val);
result = result.next;
Assert.assertEquals(2, result.val);
result = result.next;
Assert.assertEquals(3, result.val);
result = result.next;
Assert.assertEquals(4, result.val);
result = result.next;
Assert.assertEquals(4, result.val);
result = result.next;
Assert.assertEquals(5, result.val);
result = result.next;
Assert.assertEquals(6, result.val);
}
}