public static List<Integer> mergeK(int k, Iterator<Integer> a, Iterator<Integer> b) {
Integer currA = (a.hasNext() ? a.next() : null);
Integer currB = (b.hasNext() ? b.next() : null);
List<Integer> toR = new LinkedList<Integer>();
while (toR.size() != k) {
if (currA == null && currB == null) // if there's no more values, we're done
return toR;
if (currA == null || (currB != null && currA >= currB)) {
toR.add(currB);
currB = (b.hasNext() ? b.next() : null);
} else if (currB == null || currA < currB) {
toR.add(currA);
currA = (a.hasNext() ? a.next() : null);
}
}
return toR;
}
Comments