原题链接:
https://leetcode.cn/problems/merge-k-sorted-lists/
解法1: 堆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
class Solution { public ListNode mergeKLists(ListNode[] lists) { PriorityQueue<ListNode>heap = new PriorityQueue<>((o1,o2) ->{ return o1.val - o2.val; });
for(var node : lists){ if(node != null){ heap.offer(node); } }
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (!heap.isEmpty()){ var node = heap.poll(); cur.next = node; cur = cur.next; if(node.next != null){ heap.offer(cur.next); } }
return dummy.next;
} }
|
解法2: 分治
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution {
public ListNode mergeKLists(ListNode[] lists) { return mergeKLists(lists,0, lists.length); }
private ListNode mergeKLists(ListNode[] lists, int i, int j) { int m = j - i;
if(m == 0){ return null; }
if(m == 1){ return lists[i]; }
var left = mergeKLists(lists,i, i + m / 2); var right = mergeKLists(lists,i + m / 2 , j);
return mergeTwoLists(left,right);
}
private ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(0); ListNode cur = dummy; while(list1 != null && list2!=null){ if(list1.val < list2.val){ cur.next = new ListNode(list1.val); list1 = list1.next; }else{ cur.next = new ListNode(list2.val); list2 = list2.next; }
cur = cur.next; } cur.next = list1 != null ? list1 : list2; return dummy.next; } }
|