LeetCode——Peeking Iterator
2015-11-02 20:30
239 查看
先自己写了个简单粗糙的,然后又看了提示中给的参考答案,模仿着写了一个
基本思路是,用变量hasPeeked判断peekedElement保存的是否为所需的元素,若是,则无需调用基类的next()函数,直接使用这个变量。如此一来,增加peek功能不影响时间复杂度。
// 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功能不影响时间复杂度。
相关文章推荐
- C宏展开的几个注意事项
- 数据结构例程——图的遍历
- 删除MAC应用程序的4种办法
- WPF如何使用触发器
- Codeforces Round #327 (Div. 1) 解题报告
- 【CODEFORCES】 B. Friends and Presents
- 开发
- 宏
- Sharepoint2010新建一个用户的方法
- JAVA DATE解析(时间戳解析为固定格式)
- Daily Scrumming* 2015.11.2(Day 14)
- java方法创建
- Qt头文件中的QT_BEGIN_NAMESPACE
- 动态网站开发技术学习1:走进ASP.NET
- c++ string类详解
- 爬虫技术浅析
- Emmy Noether传记资料(2010-01-27 23:37:43)
- 今天学一招 android dimen中设置不带单位的数值
- android蓝牙的调试(博通蓝牙工作 and 低功耗模式)
- 两种include方式及filter中的dispatcher解析