RyanMarcus icon

Merge iterators

RyanMarcus | PRO | 03/27/16 08:13:30 PM UTC | 0 ⭐ | 268 👁️ | Never ⏰ | []
Java |

630 B

|

None

|

0 👍

/

0 👎

    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