284. 顶端迭代器

284. 顶端迭代器

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
请你设计一个迭代器,除了支持 hasNext 和 next 操作外,还支持 peek 操作。

实现 PeekingIterator 类:

PeekingIterator(int[] nums) 使用指定整数数组 nums 初始化迭代器。
int next() 返回数组中的下一个元素,并将指针移动到下个元素处。
bool hasNext() 如果数组中存在下一个元素,返回 true ;否则,返回 false
int peek() 返回数组中的下一个元素,但 不 移动指针。
 

示例:

输入:
["PeekingIterator", "next", "peek", "next", "next", "hasNext"]
[[[1, 2, 3]], [], [], [], [], []]
输出:
[null, 1, 2, 2, 3, false]

解释:
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // 返回 1 ,指针移动到下一个元素 [1,2,3]
peekingIterator.peek(); // 返回 2 ,指针未发生移动 [1,2,3]
peekingIterator.next(); // 返回 2 ,指针移动到下一个元素 [1,2,3]
peekingIterator.next(); // 返回 3 ,指针移动到下一个元素 [1,2,3]
peekingIterator.hasNext(); // 返回 False
 

提示:

1 <= nums.length <= 1000
1 <= nums[i] <= 1000
对 next 和 peek 的调用均有效
next、hasNext 和 peek 最多调用  1000

题目思路

  • 简单迭代器,主要考察迭代器的理解知识,常规的迭代器的「访问」只支持两种操作
  • hasNext() 操作:如果存在下一元素,返回 True,否则返回 False。实现上,就是判断游标是否到达结尾位置;
  • next() 操作:返回下一元素(当不存在下一元素时,返回 null)。实现上,就是返回游标指向的元素,并让游标后移。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* 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);
*
* // Returns the next element in the iteration.
* int next();
*
* // Returns true if the iteration has more elements.
* bool hasNext() const;
* };
*/

class PeekingIterator : public Iterator {
private:
int _next;
bool _hasNext;

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.
_hasNext = Iterator::hasNext();
if(_hasNext) _next = Iterator::next();
}

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

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
int dummy = _next;
_hasNext = Iterator::hasNext();
if(_hasNext) _next = Iterator::next();
return dummy;
}

bool hasNext() const {
return _hasNext;
}
};

复杂度

  • 时间复杂度:O(n)

  • 空间复杂度:O(n)


284. 顶端迭代器
https://chaggle.github.io/2021/10/05/Leetcode/284/
作者
chaggle
发布于
2021年10月5日
许可协议