美文网首页
281. Zigzag Iterator

281. Zigzag Iterator

作者: Super_Alan | 来源:发表于2018-04-19 06:58 被阅读0次

    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()

    相关文章

      网友评论

          本文标题:281. Zigzag Iterator

          本文链接:https://www.haomeiwen.com/subject/ukeikftx.html