Skip to content

Commit e1702f8

Browse files
committed
Runtime: 86 ms (Top 46.9%) | Memory: 54.48 MB (Top 31.0%)
1 parent be662f0 commit e1702f8

File tree

1 file changed

+65
-14
lines changed

1 file changed

+65
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,73 @@
1+
// Runtime: 86 ms (Top 46.9%) | Memory: 54.48 MB (Top 31.0%)
2+
3+
/**
4+
* // This is the interface that allows for creating nested lists.
5+
* // You should not implement it, or speculate about its implementation
6+
* function NestedInteger() {
7+
*
8+
* Return true if this NestedInteger holds a single integer, rather than a nested list.
9+
* @return {boolean}
10+
* this.isInteger = function() {
11+
* ...
12+
* };
13+
*
14+
* Return the single integer that this NestedInteger holds, if it holds a single integer
15+
* Return null if this NestedInteger holds a nested list
16+
* @return {integer}
17+
* this.getInteger = function() {
18+
* ...
19+
* };
20+
*
21+
* Return the nested list that this NestedInteger holds, if it holds a nested list
22+
* Return null if this NestedInteger holds a single integer
23+
* @return {NestedInteger[]}
24+
* this.getList = function() {
25+
* ...
26+
* };
27+
* };
28+
*/
29+
/**
30+
* @constructor
31+
* @param {NestedInteger[]} nestedList
32+
*/
133
var NestedIterator = function(nestedList) {
2-
this.integers = []
3-
this.index = 0
4-
this.flatten(nestedList)
34+
this.nestedList = []
35+
this.ptr = 0
36+
const dfs = (elem) => {
37+
if(!elem.isInteger()) {
38+
let list = elem.getList()
39+
for(let i = 0;i<list.length;i++) {
40+
dfs(list[i])
41+
}
42+
}else {
43+
this.nestedList.push(elem.getInteger())
44+
}
45+
}
46+
for(let i = 0;i<nestedList.length;i++) {
47+
dfs(nestedList[i])
48+
}
549
};
50+
51+
52+
/**
53+
* @this NestedIterator
54+
* @returns {boolean}
55+
*/
656
NestedIterator.prototype.hasNext = function() {
7-
return this.index < this.integers.length;
57+
if(this.ptr < this.nestedList.length) return true
58+
else return false
859
};
960

61+
/**
62+
* @this NestedIterator
63+
* @returns {integer}
64+
*/
1065
NestedIterator.prototype.next = function() {
11-
return this.integers[this.index++];
66+
return this.nestedList[this.ptr++]
1267
};
1368

14-
NestedIterator.prototype.flatten = function(list) {
15-
for(member of list){
16-
if(member.isInteger()){
17-
this.integers.push(member.getInteger())
18-
} else {
19-
this.flatten(member.getList())
20-
}
21-
}
22-
};
69+
/**
70+
* Your NestedIterator will be called like this:
71+
* var i = new NestedIterator(nestedList), a = [];
72+
* while (i.hasNext()) a.push(i.next());
73+
*/

0 commit comments

Comments
 (0)