Concise Java: O(1) memory by caching next variable. beats 92%


  • 0
    R
    class PeekingIterator implements Iterator<Integer> {
    
        private int peekValue;
        private boolean peeked;
        private Iterator<Integer> itr;
    
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    // initialize any member here.
    	    peeked = false;
    	    peekValue = 0;
    	    this.itr = iterator;
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	public Integer peek() {
            if (peeked) {
                return peekValue;
            }
                peeked = true;
                return peekValue = itr.next();
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	@Override
    	public Integer next() {
    	    if (peeked) {
    	        peeked = false;
    	        return peekValue;
    	    }
    	    return itr.next();
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return peeked ? true : itr.hasNext();
    	}
    }
    

Log in to reply
 

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