Open sofish opened 8 years ago
丑的一起看:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* function NestedInteger() {
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* @return {boolean}
* this.isInteger = function() {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* @return {integer}
* this.getInteger = function() {
* ...
* };
*
* Return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer
* @return {NestedInteger[]}
* this.getList = function() {
* ...
* };
* };
*/
/**
* @constructor
* @param {NestedInteger[]} nestedList
*/
var NestedIterator = function(nestedList) {
this.nestedList = nestedList;
this.tmp = [];
};
NestedIterator.prototype.flatten = function(arr, ret) {
if(!ret) ret = [];
arr = arr.getList ? arr.getList() : arr;
for(var i = 0, j = arr.length; i < j; i++) {
Array.isArray(arr[i].getList()) ? this.flatten(arr[i].getList(), ret) : ret.push(arr[i].getInteger());
}
return ret;
};
/**
* @this NestedIterator
* @returns {boolean}
*/
NestedIterator.prototype.hasNext = function() {
var tmp = this.nestedList[0];
while(tmp && tmp.getList() && this.flatten(tmp.getList()).toString() === '') {
this.nestedList.shift();
tmp = this.nestedList[0];
}
return this.nestedList.length || this.tmp.length;
};
/**
* @this NestedIterator
* @returns {integer}
*/
NestedIterator.prototype.next = function() {
if(this.tmp.length) return this.tmp.shift();
var ret = this.nestedList.shift();
if(ret.isInteger()) {
ret = ret.getInteger();
} else {
[].unshift.apply(this.tmp, this.flatten(ret));
ret = this.tmp.shift();
}
return ret;
};
/**
* Your NestedIterator will be called like this:
* var i = new NestedIterator(nestedList), a = [];
* while (i.hasNext()) a.push(i.next());
*/
突然想起 LeetCode,这是一个我不喜欢的地方,不过既然想去就去刷一刷。刷了几题觉得有时候就是很偏见的的玩意,比如奖字符串中的元音反转,也就是
hello
会变成holle
,也就玩玩。准备结束刷新到 https://leetcode.com/problems/flatten-nested-list-iterator/ ,然后默默在编辑器写后运行,跑过自己本地的 Testcase,但是贴上去竟然出错。代码如下:
运行起来是没问题的,但是要求并!不!是!一!个!纯!数!组!所以呵呵哒,总的来说,就是一个奇怪的古老程序员喜欢的复杂的数据结构,所以实现起来也真是:垃圾结果导致垃圾代码。
重要的话已经吐了,再见~