-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
42 lines (39 loc) · 1.38 KB
/
MergeKSortedLists.java
File metadata and controls
42 lines (39 loc) · 1.38 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
import common.ListNode;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.IntStream;
/*
* https://leetcode.com/problems/merge-k-sorted-lists/
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
Optional<Integer> maybeMinIndex =
IntStream
.range(0, lists.length)
.boxed()
.filter(integer -> lists[integer] != null)
.min(Comparator.comparingInt(value -> lists[value].val));
if (maybeMinIndex.isEmpty()) {
return null;
}
Integer minIndex = maybeMinIndex.get();
ListNode head = lists[minIndex];
lists[minIndex] = head.next;
head.next = mergeKLists(lists);
return head;
}
public static void main(String[] args) {
System.out.println(new MergeKSortedLists().mergeKLists(
new ListNode[]{
new ListNode(1,
new ListNode(4,
new ListNode(5))),
new ListNode(1,
new ListNode(3,
new ListNode(4))),
new ListNode(2,
new ListNode(6))
}
)); // 1,1,2,3,4,4,5,6
}
}