Skip to content

Commit 17ed31f

Browse files
authored
Refactored Merge K Sorted Lists.java
1 parent 691f418 commit 17ed31f

File tree

1 file changed

+21
-33
lines changed

1 file changed

+21
-33
lines changed

Hard/Merge K Sorted Lists.java

Lines changed: 21 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,41 +3,29 @@
33
* public class ListNode {
44
* int val;
55
* ListNode next;
6-
* ListNode(int x) { val = x; }
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
79
* }
810
*/
911
class Solution {
10-
public ListNode mergeKLists(ListNode[] lists) {
11-
if (lists.length == 0) {
12-
return null;
13-
}
14-
15-
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
16-
@Override
17-
public int compare(ListNode o1, ListNode o2) {
18-
return o1.val - o2.val;
19-
}
20-
});
21-
22-
for (int i = 0; i < lists.length; i++) {
23-
if (lists[i] != null) {
24-
queue.add(lists[i]);
25-
}
26-
}
27-
28-
ListNode head = new ListNode(0);
29-
ListNode p = head;
30-
31-
while (!queue.isEmpty()) {
32-
ListNode node = queue.poll();
33-
p.next = node;
34-
if (node.next != null) {
35-
queue.add(node.next);
36-
}
37-
38-
p = p.next;
39-
}
40-
41-
return head.next;
12+
public ListNode mergeKLists(ListNode[] lists) {
13+
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
14+
for (ListNode listNode : lists) {
15+
if (listNode != null) {
16+
pq.add(listNode);
17+
}
4218
}
19+
ListNode dummy = new ListNode(0);
20+
ListNode curr = dummy;
21+
while (!pq.isEmpty()) {
22+
ListNode removed = pq.remove();
23+
curr.next = new ListNode(removed.val);
24+
curr = curr.next;
25+
if (removed.next != null) {
26+
pq.add(removed.next);
27+
}
28+
}
29+
return dummy.next;
30+
}
4331
}

0 commit comments

Comments
 (0)