-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedlists.java
More file actions
74 lines (60 loc) · 1.8 KB
/
MergeSortedlists.java
File metadata and controls
74 lines (60 loc) · 1.8 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
import java.util.PriorityQueue;
/**
* Leetcode problem #23, Merge k Sorted Lists
* https://leetcode.com/problems/merge-k-sorted-lists/
* Using min heap soultion, time complexity O(n), space complexity O(k)
*/
public class MergeSortedlists {
public static void main(String[] args) {
ListNode[] lists = {
createList(new int[] { 1, 4, 5 }),
createList(new int[] { 1, 3, 4 }),
createList(new int[] { 2, 6 })
};
ListNode node = mergeKLists(lists);
while (node != null) {
System.out.printf("%d ", node.val);
node = node.next;
}
System.out.println();
}
public static ListNode createList(int[] nums) {
ListNode head = new ListNode();
ListNode ptr = head;
for (int num : nums) {
ptr.next = new ListNode(num);
ptr = ptr.next;
}
return head.next;
}
public static ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);
ListNode head = new ListNode(), curNode = head;
for (ListNode list : lists) {
if (list == null)
continue;
minHeap.add(list);
}
while (!minHeap.isEmpty()) {
ListNode node = minHeap.poll();
if (node.next != null)
minHeap.add(node.next);
curNode.next = node;
curNode = curNode.next;
}
return head.next;
}
static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}