C++ solution, 2 extra variable

  • 0
    class PeekingIterator : public Iterator {
    	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() {
    	        hasCacheNext = false;
    	        return cacheItem;
    	    return Iterator::next();
    	bool hasNext() const {
    	        return true;
    	    return Iterator::hasNext();
        bool hasCacheNext;
        int cacheItem;

Log in to reply

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