Java straightforward solution with explaination - beats 94.59% of java submissions


  • 0
    L

    Your runtime beats 94.59% of java submissions.
    12 / 12 test cases passed.
    Status: Accepted
    Runtime: 90 ms

    public class PeekingIterator implements Iterator<Integer> {
        private Iterator<Integer> iter;
        private Integer peek;
    
        public PeekingIterator(Iterator<Integer> iterator) {
            this.iter = iterator;
        }
    
        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            if(peek == null)
                peek = iter.next();
            return peek;
        }
    
        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            Integer next = null;
            if( peek!=null) {
                next = peek;
                peek = null;
            } else {
                next = iter.next();
            }
            return next;
        }
    
        @Override
        public boolean hasNext() {
            if( peek!=null) {
                return true;
            } else {
                return iter.hasNext();
            }
        }
    }
    

    0_1479164518841_284. Peeking Iterator.jpeg


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.