1、题目描述
2、解题思路
题目的要求是根拥有最大的权重,至于这个权重是多少就得取决于输入的嵌套序列到底嵌套了多少层,如果最多三层,那么根的权重就是 3。
因此,我们的解决思路是利用栈这个结构,具体流程如下:
1、创建一个队列 queue 和 一个栈 stack,同时定义一个变量 eachLevel 存储同一层的数字的和;
2、把输入的 nestedList 的根元素全部入队 queue;
3、获取当前队列 queue 的元素个数 size ,循环以下操作 size 次:
3.1 取出 queue 的一个元素 temp,如果这个元素是数字,则 eachLevel = eachLevel + temp;
3.2 如果是一个 list,则添加到 queue 中;
4、经过步骤 3 后,同一层的数字已经求和完毕,压入栈 stack 中。因为下一层的 list 已经压入 queue,因此,回到第 3 步。
5、当 queue 为空时,说明所有层的元素求和完毕,此时栈 stack 的每一个元素就是嵌套序列每一层的数字的求和,依次 pop 出并乘以它的索引加一的和即可。
如果文字描述看不太明白,可以配合代码理解。
3、解题代码
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* // Constructor initializes an empty nested list.
* public NestedInteger();
*
* // Constructor initializes a single integer.
* public NestedInteger(int value);
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // Set this NestedInteger to hold a single integer.
* public void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public void add(NestedInteger ni);
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
int result = 0;
if(nestedList == null || nestedList.size() == 0){
return result;
}
Queue<NestedInteger> queue = new LinkedList<NestedInteger>();
Stack<Integer> levelSum = new Stack<Integer>();
for(int i = 0; i < nestedList.size(); i++){
queue.offer(nestedList.get(i));
}
while(!queue.isEmpty()){
int size = queue.size();
int eachLevel = 0;
for(int i = 0; i < size; i++){
NestedInteger temp = queue.poll();
if(temp.isInteger()){
eachLevel += temp.getInteger();
}else{
for(NestedInteger one : temp.getList()){
queue.offer(one);
}
}
}
levelSum.push(eachLevel);
}
int n = 1;
while(!levelSum.isEmpty()){
result += n * levelSum.pop();
n++;
}
return result;
}
}