• 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:
    Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at depth 2)

    Example 2:
    Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    NestedInteger是单独的一种结构。可以是Integer,也可以是带括号的。所以有.getInteger().getList()方法

    [一句话思路]:

    不加权的次数多了之后,自然就变成加权的了

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. for循环里面会处理每个元素的,不用再用while
    2. 每一层剥皮的时候,把剩下的都加进去,用array的addAll方法

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    NestedInteger是单独的一种结构。可以是Integer,也可以是带括号的。所以有.getInteger().getList()方法

    [复杂度]:Time complexity: O(dfs的for循环 没法计算) Space complexity: O(1)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public int depthSumInverse(List<NestedInteger> nestedList) {
            //cc
            if (nestedList.isEmpty()) return 0;
            
            //ini: 
            int weighted = 0, unweighted = 0;
            
            while (!nestedList.isEmpty()) {
                //new array nextLevel
                List<NestedInteger> nextLevel = new ArrayList<NestedInteger>();
                
                //for loop
                for (NestedInteger ni : nestedList) {
                    //if integer, add to unweighted
                    if (ni.isInteger()) {
                        unweighted += ni.getInteger();
                    }else 
                     //else, addAll to nextLevel
                        nextLevel.addAll(ni.getList());
                }
                //add to unweighted;
                weighted += unweighted;
                nestedList = nextLevel;
            }
            
          return weighted;  
        }
    }
    View Code
  • 相关阅读:
    使用tornado的gen模块改善程序性能
    分析Linux内核中进程的调度(时间片轮转)-《Linux内核分析》Week2作业
    博客园配置MarsEdit客户端
    分析一个C语言程序生成的汇编代码-《Linux内核分析》Week1作业
    微信支付的开发流程
    探究加法操作的原子性
    mac下mysql数据库的配置
    从range和xrange的性能对比到yield关键字(中)
    使用装饰器时带括号与不带括号的区别
    从range和xrange的性能对比到yield关键字(上)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9378000.html
Copyright © 2020-2023  润新知