• [LeetCode] 364. Nested List Weight Sum II


    Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

    Each element is either an integer, or a list -- whose elements may also be integers or other lists.

    Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

    Example 1:

    Input: [[1,1],2,[1,1]]
    Output: 8 
    Explanation: Four 1's at depth 1, one 2 at depth 2.
    

    Example 2:

    Input: [1,[4,[6]]]
    Output: 17 
    Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17.

    加权嵌套序列和 II。

    题意跟版本一339题很像,唯一不同的是计算权重和的方式。在339题中,最外层的数字的权重越小,越内层的数字的权重越大;这道题是最外层的权重是最大的,最内层的权重是最小的。计算每一层的权重和都需要知道当前层的权重是多少,但是如何得知最外层的权重是多少呢。我这里提供一个BFS的方法。思路是遍历input,还是跟版本一一样把遍历到的NestedInteger加入queue。但是这里我们同时记录一个levelSum,也创建一个stack。当计算好当前层的和之后,将这个和入栈,这样弹出的时候,最先入栈的数字则带有最高的权重,跟题意符合。DFS的思路之后有机会我再补充。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int depthSumInverse(List<NestedInteger> nestedList) {
     3         // corner case
     4         if (nestedList == null) {
     5             return 0;
     6         }
     7 
     8         // normal case
     9         int res = 0;
    10         Queue<NestedInteger> queue = new LinkedList<>();
    11         Stack<Integer> stack = new Stack<>();
    12         queue.addAll(nestedList);
    13         while (!queue.isEmpty()) {
    14             int size = queue.size();
    15             int levelSum = 0;
    16             for (int i = 0; i < size; i++) {
    17                 NestedInteger cur = queue.poll();
    18                 if (cur.isInteger()) {
    19                     levelSum += cur.getInteger();
    20                 } else {
    21                     queue.addAll(cur.getList());
    22                 }
    23             }
    24             stack.push(levelSum);
    25         }
    26         int depth = 1;
    27         while (!stack.isEmpty()) {
    28             res += depth * stack.pop();
    29             depth++;
    30         }
    31         return res;
    32     }
    33 }

    相关题目

    339. Nested List Weight Sum

    364. Nested List Weight Sum II

    690. Employee Importance

    LeetCode 题目总结

  • 相关阅读:
    第四天 PYTHON 函数
    第四天 PYTHON 字符串格式化
    第四天 PYTHON 集合
    Linux使用sshfs挂载远程目录到本地
    linux通过安装包安装nginx和jdk
    使用ajax提交form表单,包括ajax文件上传
    Linux下mysql出错:ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
    数据库连接池
    一台机器上安装两个tomcat
    mysql优化
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13541009.html
Copyright © 2020-2023  润新知