LeetCode Peeking Iterator

284. Peeking Iterator284. Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation — it essentially peek() at the element that will be returned by the next call to next().

Example:

Assume that the iterator is initialized to the beginning of the list: [1,2,3].

Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. 
You call next() the final time and it returns 3, the last element. 
Calling hasNext() after that should return false.

Follow up: How would you extend your design to be generic and work with all types, not just integer?284. Peeking Iterator


设计预取迭代器peek(),简单题,理清思路就行。
设置两个局部变量,hasPeeked表示是否预取过,peekedVal表示预取的值。调用peek()时,调用父类的next得到peekedVal,并设置hasPeeked为true;当然如果hasPeeked本身为true时,直接返回peekedVal就好。调用next()时,如果预取了,则直接返回peekedVal,并且把hasPeeked重置为false,这点很重要;如果没预取,则调用父类的next。调用hasNext()时,如果有预取,则返回true,否则返回父类的hasNext()。
谷歌有关于peek迭代器的样例代码
完整代码如下:

class PeekingIterator : public Iterator {
private:
    bool hasPeeked;
    int peekedVal;

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

    int next()
    {
        if (hasPeeked) {
            hasPeeked = false;
            return peekedVal;
        }
        return Iterator::next();
    }
    bool hasNext() const { return hasPeeked || Iterator::hasNext(); }
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *