-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL23.java
More file actions
62 lines (60 loc) · 1.92 KB
/
L23.java
File metadata and controls
62 lines (60 loc) · 1.92 KB
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
59
60
61
62
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* 23. Merge k Sorted Lists https://leetcode.com/problems/merge-k-sorted-lists/
*
* @timeComplexity O(n)
* @spaceComplexity O(1)
*/
public class L23 {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
static class Solution {
class QueueNode {
Integer val;
int comingFrom;
QueueNode(int val, int comingFrom) {
this.val = val;
this.comingFrom = comingFrom;
}
}
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<QueueNode> heap = new PriorityQueue<>(new Comparator<QueueNode>() {
@Override
public int compare(QueueNode o1, QueueNode o2) {
return o1.val.compareTo(o2.val);
}
});
// Process first item from each list and populate the queue
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
heap.add(new QueueNode(lists[i].val, i));
}
}
if (heap.isEmpty()) {
return null;
}
ListNode head = new ListNode(0);
ListNode cur = head;
ListNode prev = cur;
while (!heap.isEmpty()) {
QueueNode item = heap.poll();
cur.val = item.val;
cur.next = new ListNode(0);
prev = cur;
cur = cur.next;
lists[item.comingFrom] = lists[item.comingFrom].next;
if (lists[item.comingFrom] != null)
heap.add(new QueueNode(lists[item.comingFrom].val, item.comingFrom));
}
prev.next = null;
return head;
}
}
}