我正在尝试解决这个问题“嵌套列表权重和”:https://leetcode.com/problems/nested-list-weight-sum/description/
问题:
给出列表[1,1, 2,1,1],返回10。(四个1位于深度2,一个2位于深度1)
这是我的解决方案。
var depthSum = function (nestedList, sum=0, depth=1) {
nestedList.forEach((val) => {
if (Array.isArray(val)) {
depth = depth+1;
return depthSum(val, sum, depth);
} else {
sum += val * depth;
}
});
return sum;
};
不知道我错过了什么。当我调试它的时候,我得到了答案,但return sum
没有起作用,我得到了一个不同的答案。
有没有人能告诉我虫子在哪?
发布于 2018-06-07 05:02:29
您可以使用Array#reduce
,并通过返回每个级别的总和来省略每个级别的sum
。
function depthSum(nestedList, level = 1) {
return nestedList.reduce((sum, val) =>
sum + (Array.isArray(val)
? depthSum(val, level + 1)
: level * val),
0);
};
console.log(depthSum([[1, 1], 2, [1, 1]]));
发布于 2018-06-07 05:03:40
所以解决这个问题的一个方法。
从你的forEach
内部返回是没有意义的,你应该做的是将递归调用的总数加到你当前的总数上。既然这样做了,就不需要让sum
成为depthSum
函数的参数
var nestedList = [[1,1],2,[1,1]];
var depthSum = function(nestedList, depth = 1) {
var sum = 0;
nestedList.forEach((val) => {
if (Array.isArray(val)) {
sum += depthSum(val, depth + 1);
} else {
sum += val * depth;
}
});
return sum;
};
console.log(depthSum(nestedList))
发布于 2018-06-07 05:09:44
根据Leetcode中代码的要求,以下是工作代码。
var depthSum = function (nestedList, depth=1) {
var res = 0;
nestedList.forEach((val) => {
if (val.isInteger() === false) {
res += depthSum(val.getList(), depth + 1);
} else {
res += val.getInteger() * depth;
}
});
return res;
};
您不能使用Array.isArray()
,因为所有成员都将返回false。而且你也不能直接访问这些值或列表。您需要通过他们的API访问。函数的输入不是简单的数组。请参考规范中的输入类型和接口,如下所示:
* 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() {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* @return {void}
* this.setInteger = function(value) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
* @return {void}
* this.add = function(elem) {
* ...
* };
*
* 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() {
* ...
* };
* };
*/
/**
* @param {NestedInteger[]} nestedList
* @return {number}
*/
https://stackoverflow.com/questions/50729417
复制相似问题