LeetCode 第23題 合並K個排序鏈表
阿新 • • 發佈:2019-01-21
color 優先 pri 輸入 left sem soft span spa
/*
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 }
LeetCode 第23題 合並K個排序鏈表