Skip to content

Commit af0b47e

Browse files
committed
Add solution #341
1 parent 6098841 commit af0b47e

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@
265265
334|[Increasing Triplet Subsequence](./0334-increasing-triplet-subsequence.js)|Medium|
266266
337|[House Robber III](./0337-house-robber-iii.js)|Medium|
267267
338|[Counting Bits](./0338-counting-bits.js)|Easy|
268+
341|[Flatten Nested List Iterator](./0341-flatten-nested-list-iterator.js)|Medium|
268269
342|[Power of Four](./0342-power-of-four.js)|Easy|
269270
344|[Reverse String](./0344-reverse-string.js)|Easy|
270271
345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* 341. Flatten Nested List Iterator
3+
* https://leetcode.com/problems/flatten-nested-list-iterator/
4+
* Difficulty: Medium
5+
*
6+
* You are given a nested list of integers nestedList. Each element is either an integer or a list
7+
* whose elements may also be integers or other lists. Implement an iterator to flatten it.
8+
*
9+
* Implement the NestedIterator class:
10+
* - NestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list
11+
* nestedList.
12+
* - int next() Returns the next integer in the nested list.
13+
* - boolean hasNext() Returns true if there are still some integers in the nested list and false
14+
* otherwise.
15+
*
16+
* Your code will be tested with the following pseudocode:
17+
* initialize iterator with nestedList
18+
* res = []
19+
* while iterator.hasNext()
20+
* append iterator.next() to the end of res
21+
* return res
22+
*
23+
* If res matches the expected flattened list, then your code will be judged as correct.
24+
*/
25+
26+
/**
27+
* @constructor
28+
* @param {NestedInteger[]} nestedList
29+
*/
30+
var NestedIterator = function(nestedList) {
31+
this.stack = [];
32+
this.flatten(nestedList);
33+
};
34+
35+
/**
36+
* @this NestedIterator
37+
* @param {NestedInteger[]} nestedList
38+
* @returns {void}
39+
*/
40+
NestedIterator.prototype.flatten = function(list) {
41+
for (let i = list.length - 1; i >= 0; i--) {
42+
this.stack.push(list[i]);
43+
}
44+
};
45+
46+
/**
47+
* @this NestedIterator
48+
* @returns {boolean}
49+
*/
50+
NestedIterator.prototype.hasNext = function() {
51+
while (this.stack.length > 0 && !this.stack[this.stack.length - 1].isInteger()) {
52+
const nested = this.stack.pop().getList();
53+
this.flatten(nested);
54+
}
55+
return this.stack.length > 0;
56+
};
57+
58+
/**
59+
* @this NestedIterator
60+
* @returns {integer}
61+
*/
62+
NestedIterator.prototype.next = function() {
63+
return this.stack.pop().getInteger();
64+
};

0 commit comments

Comments
 (0)