281. Zigzag Iterator

2018-04-19  本文已影响0人  Super_Alan

https://leetcode.com/problems/zigzag-iterator/description/

public class ZigzagIterator {
    
    private Iterator<Integer> iter1, iter2;
    private Iterator<Integer> nextIter;
    
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        iter1 = v1.iterator();
        iter2 = v2.iterator();

        // pay attention here. list1 could be empty
        nextIter = iter1.hasNext() ? iter1 : iter2;
    }

    public int next() {
        int nextInt = nextIter.next();
        
        if (nextIter == iter1 && iter2.hasNext()) {
            nextIter = iter2;
        } else if (nextIter == iter2 && iter1.hasNext()) {
            nextIter = iter1;
        }
        
        return nextInt;
    }

    public boolean hasNext() {
        return nextIter.hasNext();
        // return iter1.hasNext() || iter2.hasNext();
    }
}

Follow up

Extend to multiple lists of integers.

public class ZigzagIterator {
    private LinkedList<Iterator> iterators;
    
    public ZigzagIterator(List<List<Integer>> lists) {
        iterators = new LinkedList<Iterator>();
        
        for (List<Integer> list: lists) {
            if (list != null && !list.isEmpty()) {
                iterators.add(list.iterator());
            }
        }
    }
    
    public int next() {
        Iterator<Integer> iter = iterators.removeFirst();
        int nextInt = iter.next();
        
        if (iter.hasNext()) {
            iterators.add(iter);
        }
        
        return nextInt;
    }
    
    public boolean hasNext() {
        return !iterators.isEmpty();
    }
} 

Runtime: O(1)
Space: O(n) n is lists.size()

上一篇 下一篇

猜你喜欢

热点阅读