您的位置:首页 > 其它

LeetCode——Peeking Iterator

2015-11-02 20:30 239 查看
先自己写了个简单粗糙的,然后又看了提示中给的参考答案,模仿着写了一个

// 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.
peekedElement = Iterator::next();
hasPeeked = true;
}

// Returns the next element in the iteration without advancing the iterator.
int peek() {

if(!hasPeeked)
{
peekedElement = Iterator::next();
hasPeeked = true;
}

return peekedElement;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {

if(hasPeeked)
{
hasPeeked = false;
return peekedElement;
}
else
{
return Iterator::next();
}
}

bool hasNext() const {

return hasPeeked || Iterator::hasNext();
}

private:
int peekedElement;
bool hasPeeked;
};


基本思路是,用变量hasPeeked判断peekedElement保存的是否为所需的元素,若是,则无需调用基类的next()函数,直接使用这个变量。如此一来,增加peek功能不影响时间复杂度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: