/* 23. 合并K个排序链表 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入:[ 1->4->5, 1->3->4, 2->6]输出: 1->1->2->3->4->4->5->6 */ /** * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int * x) { val = x; } } */ /*思路1: 分治法,归并排序思路2: 优先队列*/
1 class Solution23 { 2 3 /* 4 分治法,归并排序. 5 */ 6 public ListNode mergeKLists(ListNode[] lists) { 7 if (lists == null || lists.length == 0) { 8 return null; 9 } 10 return sort(lists, 0, lists.length - 1); 11 } 12 13 ListNode sort(ListNode[] list, int left, int right) { 14 if (left < right) { 15 int mid = (left + right) >> 1; 16 ListNode le = sort(list, left, mid); 17 ListNode ri = sort(list, mid + 1, right); 18 return merge(le, ri); 19 } 20 return list[left]; 21 } 22 23 ListNode merge(ListNode le, ListNode ri) { 24 if (le == null) { 25 return ri; 26 } 27 if (ri == null) { 28 return le; 29 } 30 if (le.val < ri.val) { 31 le.next = merge(le.next, ri); 32 return le; 33 } else { 34 ri.next = merge(le, ri.next); 35 return ri; 36 } 37 } 38 39 /* 40 优先队列式. 41 */ 42 public ListNode mergeKLists2(ListNode[] lists) { 43 44 if (lists == null || lists.length == 0) { 45 return null; 46 } 47 if (lists.length == 1) { 48 return lists[0]; 49 } 50 PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val)); 51 for (ListNode list : lists) { 52 if (list != null) { 53 queue.add(list); 54 } 55 } 56 ListNode dummy = new ListNode(0); 57 ListNode curr = dummy; 58 while (!queue.isEmpty()) { 59 curr.next = queue.poll(); 60 curr = curr.next; 61 if (curr.next != null) { 62 queue.add(curr.next); 63 } 64 } 65 return dummy.next; 66 } 67 }
原文地址:https://www.cnblogs.com/rainbow-/p/10296459.html
时间: 2024-11-02 16:28:34