C++ solution, 2 extra variable


  • 0
    W
    class PeekingIterator : public Iterator {
    public:
    	PeekingIterator(const vector<int>& nums) : Iterator(nums), hasCacheNext(false), cacheItem(0) {
    	    // Initialize any member here.
    	    // **DO NOT** save a copy of nums and manipulate it directly.
    	    // You should only use the Iterator interface methods.
    	    
    	}
    
        // Returns the next element in the iteration without advancing the iterator.
    	int peek() {
            if(!hasCacheNext && hasNext()){
                cacheItem = Iterator::next();
                hasCacheNext = true;
            }
            
            return cacheItem;
    	}
    
    	// hasNext() and next() should behave the same as in the Iterator interface.
    	// Override them if needed.
    	int next() {
    	    if(hasCacheNext){
    	        hasCacheNext = false;
    	        return cacheItem;
    	    }
    	    
    	    return Iterator::next();
    	}
    
    	bool hasNext() const {
    	    if(hasCacheNext)
    	        return true;
    	    
    	    return Iterator::hasNext();
    	}
    	    
    private:
        bool hasCacheNext;
        int cacheItem;
    };
    

Log in to reply
 

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