diff --git a/README.md b/README.md index 1b08c20..46021cf 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 278 |[First Bad Version](https://leetcode.com/problems/first-bad-version)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/278.%20First%20Bad%20Version.md)|Easy| | | 279 |[Perfect Squares](https://leetcode.com/problems/perfect-squares/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/279.%20Perfect%20Squares.md)|Medium| | | 283 |[Move Zeroes](https://leetcode.com/problems/move-zeroes)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/283.%20Move%20Zeroes.md)|Easy| | +| 284 |[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)|[C++](solutions/284.%20Peeking%20Iterator.md)|Medium| | | 287 |[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/287.%20Find%20the%20Duplicate%20Number.md)|Medium| | | 289 |[Game of Life](https://leetcode.com/problems/game-of-life/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/289.%20Game%20of%20Life.md)|Medium| | | 290 |[Word Pattern](https://leetcode.com/problems/word-pattern)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/290.%20Word%20Pattern.md)|Easy| | diff --git a/solutions/284. Peeking Iterator.md b/solutions/284. Peeking Iterator.md new file mode 100644 index 0000000..b6bb22f --- /dev/null +++ b/solutions/284. Peeking Iterator.md @@ -0,0 +1,61 @@ +# [284. Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) + +# 思路 + +我们有了一个只支持`next`和`hasNext`方法的迭代器类,让我们实现一个子类,要求增添一个`peek`方法。 + +## 思路一 +我们想实现的`peek`是只返回当前元素而不考虑指针后移。但每次调用基类的`next`时,返回当前元素后都会后移指针。那么我们可以考虑用一个变量`value`在调用基类的`next`时缓存当前元素,这样的话即使指针后移了,我们调用`peek`时也能直接返回value。为此我们需要一个bool变量`flag`来指示`value`是否存放了在之后调用`peek`和`next`应该返回的值。 + + +## 思路二 +还有一个比较tricky的方法:`peek`时创建一个当前指针对应的副本,由于是局部变量,所以调用结束后会被销毁,所以并没有任何内存问题。 + +# C++ + +## 思路一 +``` C++ +class PeekingIterator : public Iterator { +private: + bool flag; + int value; + +public: + PeekingIterator(const vector& nums) : Iterator(nums) { + flag = false; // value是否存放了peek和next应该返回的值 + } + + int peek(){ + if(!flag) value = Iterator::next(); + flag = true; + return value; + } + + int next() { + if(!flag) return Iterator::next(); + flag = false; + return value; + } + + bool hasNext() const { + return flag || Iterator::hasNext(); + } +}; +``` + +## 思路二 +``` C++ +class PeekingIterator : public Iterator { +public: + PeekingIterator(const vector& nums) : Iterator(nums) {} + + int peek(){ + // 调用Iterator(const Iterator& iter)创造一个副本 + return Iterator(*this).next(); + } + +// int next() {} +// bool hasNext() const {} +}; +``` +