-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_k_Sorted_Lists.java
More file actions
76 lines (64 loc) · 1.95 KB
/
Copy pathMerge_k_Sorted_Lists.java
File metadata and controls
76 lines (64 loc) · 1.95 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
23. Merge k Sorted Lists
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;
* }
* }
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) return null;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (ListNode node : lists)
if (node!=null)
queue.add(node);
while (!queue.isEmpty()) {
tail.next = queue.poll();
tail = tail.next;
if (tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}
////////////////////////////////////////////////////////////////////////////////
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode head = null;
for (ListNode node : lists)
head = mergeTwoLists(head, node);
return head;
}
private ListNode mergeTwoLists(ListNode head1, ListNode head2) {
if (head1 == null || head2 == null)
return head1 == null ? head2 : head1;
if (head1.val < head2.val) {
head1.next = mergeTwoLists(head1.next, head2);
return head1;
} else {
head2.next = mergeTwoLists(head2.next, head1);
return head2;
}
}
}