LeetCode--023--合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
方法1:分治
time:O(nlogk) where k is the number of linked list
space:O(n)
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 class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if(lists == null || lists.length == 0)return null; 12 return sort(lists,0,lists.length - 1); 13 } 14 public ListNode sort(ListNode[] lists,int lo,int hi){ 15 if(lo >= hi) return lists[lo];//奇数个的时候,两两合并会多出一个,此语句用于返回该list,在下一次进行合并 16 int mid = (hi - lo) / 2 + lo; 17 ListNode l1 = sort(lists,lo,mid); 18 ListNode l2 = sort(lists,mid+1,hi); 19 return merge(l1,l2); 20 } 21 public ListNode merge(ListNode l1,ListNode l2){ 22 if(l1 == null) return l2; 23 if(l2 == null) return l1; 24 if(l1.val < l2.val){ 25 l1.next = merge(l1.next,l2); 26 return l1; 27 } 28 l2.next = merge(l1,l2.next); 29 return l2; 30 } 31 }
方法2:优先级队列
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 class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if(lists == null || lists.length == 0)return null; 12 PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length,(a,b)->a.val-b.val); 13 ListNode dummy = new ListNode(0); 14 ListNode cur = dummy; 15 16 for(ListNode list : lists){ 17 if(list != null){ 18 queue.add(list); 19 } 20 } 21 while(!queue.isEmpty()){ 22 cur.next = queue.poll(); 23 cur = cur.next; 24 if(cur.next != null){ 25 queue.add(cur.next); 26 } 27 } 28 return dummy.next; 29 } 30 31 }
2019-04-19 10:07:41