-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKsortedLists.java
More file actions
57 lines (47 loc) · 1.08 KB
/
Copy pathMergeKsortedLists.java
File metadata and controls
57 lines (47 loc) · 1.08 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//time:O(nlogk);
//space: O (N)
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//corner case
if(lists == null || lists.length == 0) return null;
//create priorityQueue
Queue<ListNode> pq = new PriorityQueue<>(Lists.length, (a,b) -> (a.val - b.val));
//adding each head of list into pq
for(int i = 0; i < lists.length; i++){
if(lists[i] != null) pq.offer(lists[i]);
}
//compare
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while(!pq.isEmpty()){
ListNode head = pq.poll();
tail.next = head;
tail = head;
if(head.next != null) pq.offer(head.next);
}
return dummy.next;
}
}
// 1->4->5
// 1->3->4
// 2->6
// 4->5
// 1->3->4
// 2->6
// res: 1
// 4->5
// 3->4
// 2->6
// res: 1->1
// 4->5
// 3->4
// 6
// res: 1->1->2