Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.html
[解題思路]node
之前的解法的時間複雜度太高,經過在網上搜索,獲得優化的時間複雜度:O(n*lgk)優化
維護一個大小爲k的最小堆,每次獲得一個最小值,重複n次spa
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode mergeKLists(ArrayList<ListNode> lists) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 ListNode head = null; 17 int len = lists.size(); 18 if(len <= 1) 19 return null; 20 head = merge2List(lists.get(0), lists.get(1)); 21 for(int i = 2; i < len; i++){ 22 head = merge2List(lists.get(i), head); 23 } 24 return head; 25 26 } 27 28 public ListNode merge2List(ListNode node1, ListNode node2){ 29 ListNode head = null; 30 ListNode tmp = head; 31 while(node1 != null && node2 != null){ 32 if(node1.val <= node2.val){ 33 ListNode node = new ListNode(node1.val); 34 tmp = node; 35 tmp = tmp.next; 36 } else { 37 ListNode node = new ListNode(node2.val); 38 tmp = node; 39 tmp = tmp.next; 40 } 41 node1 = node1.next; 42 node2 = node2.next; 43 } 44 45 while(node1 != null){ 46 ListNode node = new ListNode(node1.val); 47 tmp = node; 48 tmp = tmp.next; 49 node1 = node1.next; 50 } 51 52 while(node2 != null){ 53 ListNode node = new ListNode(node2.val); 54 tmp = node; 55 tmp = tmp.next; 56 node2 = node2.next; 57 } 58 return head; 59 60 } 61 }
上一版本有bug,修復以下: .net
1 public class Solution { 2 public ListNode mergeKLists(ArrayList<ListNode> lists) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 ListNode head = null; 6 int len = lists.size(); 7 if(len == 0) 8 return null; 9 else if(len == 1){ 10 return lists.get(0); 11 } 12 head = merge2List(lists.get(0), lists.get(1)); 13 for(int i = 2; i < len; i++){ 14 head = merge2List(lists.get(i), head); 15 } 16 return head; 17 18 } 19 20 public ListNode merge2List(ListNode node1, ListNode node2){ 21 ListNode head = new ListNode(Integer.MIN_VALUE); 22 ListNode tmp = head; 23 while(node1 != null && node2 != null){ 24 if(node1.val <= node2.val){ 25 ListNode node = new ListNode(node1.val); 26 tmp.next = node; 27 tmp = tmp.next; 28 node1 = node1.next; 29 } else { 30 ListNode node = new ListNode(node2.val); 31 tmp.next = node; 32 tmp = tmp.next; 33 node2 = node2.next; 34 } 35 } 36 37 if(node1 != null){ 38 tmp.next = node1; 39 } 40 41 if(node2 != null){ 42 tmp.next = node2; 43 } 44 head = head.next; 45 return head; 46 47 } 48 }
http://blog.csdn.net/zyfo2/article/details/8682727code
http://tech-wonderland.net/blog/leetcode-merge-k-sorted-lists.htmlhtm