284. Peeking Iterator


做题历程:

  1. 2016/Oct/19,本题应该不止做了一次,本次独立解出,大概耗时21分钟

这是一道设计题,不过确实不难。。。说白了就是怎么实现peek(),这个往简单了说其实就是搞一个cache记录下一个元素,如果遇到next()则更新cache,否则保持cache不变即可。。最终代码如下:

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
    struct Data;
    Data* data;
public:
    Iterator(const vector<int>& nums);
    Iterator(const Iterator& iter);
    virtual ~Iterator();
    // Returns the next element in the iteration.
    int next();
    // Returns true if the iteration has more elements.
    bool hasNext() const;
};


class PeekingIterator : public Iterator {
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.
        cache = make_pair(false, 0);
    }

    // Returns the next element in the iteration without advancing the iterator.
    int peek() {
        if (cache.first == false) {
            cache.first = true;
            cache.second = Iterator::next();
        }
        return cache.second;
    }

    // hasNext() and next() should behave the same as in the Iterator interface.
    // Override them if needed.
    int next() {
        if (cache.first == false) {
            peek();
        }
        cache.first = false;
        return cache.second;
    }

    bool hasNext() const {
        return cache.first || Iterator::hasNext();
    }
private:
    pair<bool, int> cache;
};

results matching ""

    No results matching ""