題目: 合並k個排序將k個已排序的鏈表合並為一個排好序的鏈表,並分析其時間復雜度 。
解題思路: 類似於歸並排序的思想,lists中存放的是多個單鏈表,將lists的頭和尾兩個鏈表合並,放在頭,頭向后移動,尾向前移動,繼續合並,直到頭和尾相等,此時已經歸並了一半, 然后以同樣的方法又重新開始歸並剩下的一半。時間復雜度是O(logn),合並兩個鏈表的時間復雜度是O(n),則總的時間復雜度大概是O(nlogn);合並兩個單鏈表算法可以參考Leetcode21中的解法:http://www.cnblogs.com/leavescy/p/5879625.html
代碼如下:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if(lists == null|| lists.length == 0) 12 return null; 13 if(lists.length == 1) 14 return lists[0]; 15 int end = lists.length - 1; 16 int begin = 0; 17 while(end > 0) // 將lists的頭和尾進行歸並,然后將結果存放在頭,頭向后移動,尾向前移動,直到begin=end,則已經歸並了一半,此時將begin=0,繼續歸並 18 { 19 begin = 0; 20 while(begin < end) 21 { 22 lists[begin] = combineTwoList(lists[begin], lists[end]); 23 begin ++; 24 end --; 25 } 26 } 27 28 return lists[0]; 29 } 30 public ListNode combineTwoList(ListNode head1, ListNode head2) // head1和head2為頭節點的兩個單鏈表的合並 31 { 32 if(head1 == null && head2 == null) // 如果兩個單鏈表都不存在,則返回null 33 return null; 34 if(head1 == null) // 如果head1不存在,則直接返回head2 35 return head2; 36 if(head2 == null) 37 return head1; 38 ListNode pHead = null; 39 if(head1.val > head2.val) // 根據head1與head2的值,決定頭節點 40 { 41 pHead = head2; 42 pHead.next = combineTwoList(head1, head2.next); 43 } 44 else 45 { 46 pHead = head1; 47 pHead.next = combineTwoList(head1.next, head2); 48 } 49 return pHead; 50 } 51 }