forked from algorhythms/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
48 lines (45 loc) · 1.15 KB
/
Copy pathSolution.java
File metadata and controls
48 lines (45 loc) · 1.15 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
package MergekSortedLists;
import commons.datastructures.ListNode;
import java.util.List;
import java.util.PriorityQueue;
/**
* User: Danyang
* Date: 1/17/2015
* Time: 20:38
*
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
public class Solution {
/**
* Heap With ListNode
* m lists, with n nodes each
* O(lg m * mn)
*
* -------------------
| | | | | |
| | | | | |
| | | | | |
| | | | | |
*
*
* @param lists
* @return
*/
public ListNode mergeKLists(List<ListNode> lists) {
ListNode dummy = new ListNode(0);
PriorityQueue<ListNode> pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1.val, o2.val));
for(ListNode cur: lists) { // stream may TLE
if(cur!=null)
pq.add(cur);
}
ListNode pre = dummy;
while(pq.size()>0) {
ListNode cur = pq.poll();
if(cur.next!=null)
pq.add(cur.next);
pre.next = cur;
pre = pre.next;
}
return dummy.next;
}
}