-
Notifications
You must be signed in to change notification settings - Fork 4
/
MergeKSortedLists.java
53 lines (46 loc) · 1.32 KB
/
MergeKSortedLists.java
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
package com.dbc;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class MergeKSortedLists {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode mergeKLists(ListNode[] lists) {
Queue<int[]> queue = new PriorityQueue<>((a, b) -> a[0] - b[0]);
Map<Integer, ListNode> map = new HashMap<>();
int count = 0;
for (ListNode node : lists) {
if (node != null) {
queue.offer(new int[]{node.val, count});
map.put(count, node);
count++;
}
}
ListNode res = new ListNode();
ListNode preHead = res;
while (!queue.isEmpty()) {
int[] nodeCount = queue.poll();
ListNode node = map.get(nodeCount[1]);
preHead.next = node;
preHead = preHead.next;
if (node.next != null) {
queue.offer(new int[]{node.next.val, count});
map.put(count, node.next);
count++;
}
}
return res.next;
}
}