标签:leetcode解题报告 算法 java 递归 面试题
https://oj.leetcode.com/problems/merge-k-sorted-lists/解题报告:先不考虑任何优化,最朴素的实现方法就是遍历一遍List<ListNode>,对其中每个链表同当前链表做一遍类似于归并排序最后一步的merge操作。
算法复杂度是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; } }
所以借鉴归并递归的方法,以下代码顺利AC了。时间复杂度为: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 解题报告
标签:leetcode解题报告 算法 java 递归 面试题
原文地址:http://blog.csdn.net/worldwindjp/article/details/39989005