Concise Java solution beats 99.52%, 95ms by caching next element


  • 8
    V
    class PeekingIterator implements Iterator<Integer> {
    
        Integer peek;  // use to visit and store the next element
        Iterator<Integer> it;
        
    	public PeekingIterator(Iterator<Integer> iterator) {
    	    it = iterator;
            peek = it.hasNext()?it.next():null;
    	}
    
    	public Integer peek() {
            return peek;        
    	}
    
    	@Override
    	public Integer next() {
            if (peek==null) throw new java.util.NoSuchElementException();
    	    Integer ret = peek;
            peek = it.hasNext()?it.next():null;
            return ret;
    	}
    
    	@Override
    	public boolean hasNext() {
    	    return peek!=null;
    	}
    	
    }

Log in to reply
 

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