Https://oj.leetcode.com/problems/merge-k-sorted-lists/
Merge K sorted arrays and analyze the complexity of the entire algorithm.
Solution report: the simplest implementation method is to traverse the list <listnode>, perform a merge operation similar to the last step of merging and sorting for each linked list and the current linked list.
The algorithm complexity is O (kN)
public class Solution { ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode head = new ListNode(-1); ListNode current = head; while(list1!=null&&list2!=null) { if(list1.val<list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if(list1!=null) { current.next = list1; } else { current.next = list2; } return head.next; } public ListNode mergeKLists(List<ListNode> lists) { if(lists==null||lists.size()==0) { return null; } ListNode head = lists.get(0); for(int i=1;i<lists.size();i++) { head = mergeTwoLists(head, lists.get(i)); } return head; }}
The above method TLE, I checked it online and noticed that by using the Merge Sorting Algorithm, the time complexity of the chain table sorting can be reduced to O (nlgn). The specific calculation formula is:
Therefore, the following code is successfully AC by referring to the merge recursion method. Time Complexity: O (nlogk)
public class Solution { ListNode merge2Lists(ListNode list1, ListNode list2) { ListNode head = new ListNode(-1); ListNode current = head; while(list1!=null&&list2!=null) { if(list1.val<list2.val) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if(list1!=null) { current.next = list1; } else { current.next = list2; } return head.next; } public ListNode mergeKLists(List<ListNode> lists) { if(lists==null||lists.size()==0) { return null; } if(lists.size()==1) { return lists.get(0); } int length = lists.size() ; int mid = (length - 1)/2 ; ListNode l1 = mergeKLists(lists.subList(0,mid + 1)) ; ListNode l2 = mergeKLists(lists.subList(mid + 1,length)) ; return merge2Lists(l1,l2) ; }}
Leetcode merge K sorted lists solution report