forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge k Sorted Lists.java
More file actions
42 lines (40 loc) · 1.04 KB
/
Merge k Sorted Lists.java
File metadata and controls
42 lines (40 loc) · 1.04 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
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if (lists == null || lists.isEmpty()) return null;
Comparator<ListNode> comp = new Comparator<ListNode>() {
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) return -1;
if (o1.val > o2.val) return 1;
return 0;
}
};
PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), comp);
for (ListNode node : lists) {
if (node != null) heap.add(node);
}
ListNode head = null, cur = null;
while (!heap.isEmpty()) {
if (head == null) {
head = heap.poll();
cur = head;
} else {
cur.next = heap.poll();
cur = cur.next;
}
if (cur.next != null) heap.add(cur.next);
}
return head;
}
}