Skip to content

Commit 20bca28

Browse files
committed
284
1 parent 857d25b commit 20bca28

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,4 +235,5 @@
235235
* [279. Perfect Squares](leetcode-279-Perfect-Squares.md)
236236
* [282. Expression Add Operators](leetcode-282-Expression-Add-Operators.md)
237237
* [283. Move Zeroes](leetcode-283-Move-Zeroes.md)
238+
* [284. Peeking Iterator](leetcode-284-Peeking-Iterator.md)
238239
* [更多](more.md)

leetcode-284-Peeking-Iterator.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# 题目描述(中等难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/284.jpg)
4+
5+
给迭代器增加一个 `peek` 功能,也就是查看下一个元素,但是不从迭代器中弹出。
6+
7+
# 解法一
8+
9+
我第一反应是直接把迭代器的元素放到 `list` 中不就实现了吗?
10+
11+
```java
12+
class PeekingIterator implements Iterator<Integer> {
13+
List<Integer> list;
14+
int cur = 0;
15+
16+
public PeekingIterator(Iterator<Integer> iterator) {
17+
// initialize any member here.
18+
list = new ArrayList<>();
19+
while (iterator.hasNext())
20+
list.add(iterator.next());
21+
22+
}
23+
24+
// Returns the next element in the iteration without advancing the iterator.
25+
public Integer peek() {
26+
return list.get(cur);
27+
}
28+
29+
// hasNext() and next() should behave the same as in the Iterator interface.
30+
// Override them if needed.
31+
@Override
32+
public Integer next() {
33+
return list.get(cur++);
34+
}
35+
36+
@Override
37+
public boolean hasNext() {
38+
return cur < list.size();
39+
}
40+
}
41+
```
42+
43+
# 解法二
44+
45+
解法一还真的通过了,觉得自己没有 get 题目的点,然后去逛 Discuss 了,原来题目想让我们这样做,分享 [这里](https://leetcode.com/problems/peeking-iterator/discuss/72558/Concise-Java-Solution) 的代码。
46+
47+
我们知道构造函数传进来的迭代器已经有了 `next``haseNext` 函数,我们需要增加 `peek` 函数。我们可以加一个缓冲变量,记录当前要返回的值。
48+
49+
`peek` 的话只需要将缓冲变量直接返回。
50+
51+
`next` 的话我们需要更新缓冲变量,然后将之前的缓冲变量返回即可。
52+
53+
```java
54+
class PeekingIterator implements Iterator<Integer> {
55+
private Integer next = null;//缓冲变量
56+
private Iterator<Integer> iter;
57+
58+
public PeekingIterator(Iterator<Integer> iterator) {
59+
// initialize any member here.
60+
iter = iterator;
61+
if (iter.hasNext()){
62+
next = iter.next();
63+
}
64+
65+
}
66+
67+
// Returns the next element in the iteration without advancing the iterator.
68+
public Integer peek() {
69+
return next;
70+
}
71+
72+
// hasNext() and next() should behave the same as in the Iterator interface.
73+
// Override them if needed.
74+
@Override
75+
public Integer next() {
76+
Integer res = next;
77+
next = iter.hasNext() ? iter.next() : null;
78+
return res;
79+
}
80+
81+
@Override
82+
public boolean hasNext() {
83+
return next != null;
84+
}
85+
}
86+
```
87+
88+
#
89+
90+
其实是比较简单的一道题,用到的思想也比较简单,增加了一个缓冲变量来实现 `peek` 的功能。

0 commit comments

Comments
 (0)