-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第十三天:数据结构的锅 #15
Milestone
Comments
丑的一起看: /**
* // 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());
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
突然想起 LeetCode,这是一个我不喜欢的地方,不过既然想去就去刷一刷。刷了几题觉得有时候就是很偏见的的玩意,比如奖字符串中的元音反转,也就是
hello
会变成holle
,也就玩玩。准备结束刷新到 https://leetcode.com/problems/flatten-nested-list-iterator/ ,然后默默在编辑器写后运行,跑过自己本地的 Testcase,但是贴上去竟然出错。代码如下:
运行起来是没问题的,但是要求并!不!是!一!个!纯!数!组!所以呵呵哒,总的来说,就是一个奇怪的古老程序员喜欢的复杂的数据结构,所以实现起来也真是:垃圾结果导致垃圾代码。
重要的话已经吐了,再见~
The text was updated successfully, but these errors were encountered: