Skip to content

Commit 844e539

Browse files
committed
Add solution #284
1 parent 039c2ad commit 844e539

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@
226226
279|[Perfect Squares](./0279-perfect-squares.js)|Medium|
227227
282|[Expression Add Operators](./0282-expression-add-operators.js)|Hard|
228228
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
229+
284|[Peeking Iterator](./0284-peeking-iterator.js)|Medium|
229230
287|[Find the Duplicate Number](./0287-find-the-duplicate-number.js)|Medium|
230231
289|[Game of Life](./0289-game-of-life.js)|Medium|
231232
290|[Word Pattern](./0290-word-pattern.js)|Easy|

solutions/0284-peeking-iterator.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 284. Peeking Iterator
3+
* https://leetcode.com/problems/peeking-iterator/
4+
* Difficulty: Medium
5+
*
6+
* Design an iterator that supports the peek operation on an existing iterator in addition to
7+
* the hasNext and the next operations.
8+
*
9+
* Implement the PeekingIterator class:
10+
* - PeekingIterator(Iterator<int> nums) Initializes the object with the given integer iterator
11+
* iterator.
12+
* - int next() Returns the next element in the array and moves the pointer to the next element.
13+
* - boolean hasNext() Returns true if there are still elements in the array.
14+
* - int peek() Returns the next element in the array without moving the pointer.
15+
*
16+
* Note: Each language may have a different implementation of the constructor and Iterator, but
17+
* they all support the int next() and boolean hasNext() functions.
18+
*/
19+
20+
/**
21+
* @param {Iterator} iterator
22+
*/
23+
var PeekingIterator = function(iterator) {
24+
this.iterator = iterator;
25+
this.peekValue = iterator.next();
26+
};
27+
28+
/**
29+
* @return {number}
30+
*/
31+
PeekingIterator.prototype.peek = function() {
32+
return this.peekValue;
33+
};
34+
35+
/**
36+
* @return {number}
37+
*/
38+
PeekingIterator.prototype.next = function() {
39+
const next = this.peekValue;
40+
this.peekValue = this.iterator.next();
41+
return next;
42+
};
43+
44+
/**
45+
* @return {boolean}
46+
*/
47+
PeekingIterator.prototype.hasNext = function() {
48+
return this.peekValue > 0;
49+
};

0 commit comments

Comments
 (0)