23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

 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         int k = lists.length;
12         ListNode dummy = new ListNode(0);
13         ListNode []p = new ListNode[k];
14         
15         for (int i = 0; i < k; ++i) {
16             p[i] = lists[i];
17         }
18         ListNode temp = dummy;
19         while (true) {
20             int pos = -1, min = -1;
21             for (int i = 0; i < k; ++i) {
22                 if (p[i] != null) {
23                     if (pos == -1 || p[i].val < min) {
24                         pos = i;
25                         min = p[i].val;
26                     }
27                 }
28             }
29             if (pos == -1) break;
30             
31             temp.next = new ListNode(p[pos].val);
32             temp = temp.next;
33             p[pos] = p[pos].next;
34             
35         }
36         return dummy.next;
37         
38     }
39 }

 

 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 
10 
11 class Solution {
12     static Comparator<ListNode> cmp = new Comparator<ListNode>() {
13         public int compare(ListNode e1, ListNode e2) {
14             return e1.val - e2.val;
15         }
16     };
17     public ListNode mergeKLists(ListNode[] lists) {
18         int k = lists.length;
19         ListNode dummy = new ListNode(0);
20         ListNode p = dummy;
21         Queue<ListNode> q = new PriorityQueue<>(cmp);
22         
23         
24         for (int i = 0; i < k; ++i) {
25             if (lists[i] != null) {
26                 q.add(lists[i]);
27             }
28         }
29         
30         while (!q.isEmpty()) {
31             ListNode temp = q.poll();
32             p.next = new ListNode(temp.val);
33             if (temp.next != null) {
34                 q.add(temp.next);
35             }
36             p = p.next;
37         }
38         return dummy.next;
39         
40     }
41 }

 

posted @ 2020-02-15 19:52  hyx1  阅读(85)  评论(0编辑  收藏  举报