forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
50 lines (39 loc) · 1.52 KB
/
Solution.java
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
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Oleg Cherednik
* @since 07.02.2019
*/
public class Solution {
public static void main(String... args) {
List<List<Integer>> sortedLists = Arrays.asList(
Arrays.asList(0, 1, 4, 5, 6, 8, 8),
Arrays.asList(0, 1, 3, 3, 3, 3, 5, 6, 7),
Arrays.asList(0, 0, 1, 3, 4, 5, 6, 6, 6, 7, 8, 8, 8)
);
System.out.println(merge(sortedLists).stream()
.map(val -> Integer.toString(val))
.collect(Collectors.joining(" ")));
}
public static List<Integer> merge(List<List<Integer>> sortedLists) {
List<Integer> res = new LinkedList<>();
Iterator<Integer>[] its = sortedLists.stream().map(List::iterator).toArray(Iterator[]::new);
Integer[] values = new Integer[sortedLists.size()];
while (true) {
int minIndex = -1;
for (int i = 0; i < values.length; i++) {
values[i] = values[i] == null && its[i].hasNext() ? its[i].next() : values[i];
if (values[i] != null)
minIndex = minIndex == -1 || values[minIndex] != null && values[minIndex] > values[i] ? i : minIndex;
}
if (minIndex == -1)
break;
res.add(values[minIndex]);
values[minIndex] = null;
}
return res;
}
}