资讯专栏INFORMATION COLUMN

[LeetCode] 339. Nested List Weight Sum

骞讳护 / 1796人阅读

Problem

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.

Example 1:

Input: [[1,1],2,[1,1]]
Output: 10
Explanation: Four 1"s at depth 2, one 2 at depth 1.
Example 2:

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

Solution
/**
 *     // @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
 *     public Integer getInteger();
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     public List getList();
 */
class Solution {
    public int depthSum(List nestedList) {
        return helper(nestedList, 1);
    }
    private int helper(List list, int level) {
        int res = 0;
        for (NestedInteger item: list) {
            if (item.isInteger()) res += (level*item.getInteger());
            else {
                res += helper(item.getList(), level+1);
            }
        }
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72410.html

相关文章

  • 364. Nested List Weight SumII

    摘要:题目解答这一题其实挺的,如果说第一道题的关键是记录层次,那么这一题的关键是把这一层的传到下一层去,代码如下关键点在于把上一层的传到下一层去,这样的话,接下来还有几层,每一层都会加上这个也就等于乘以了它的层数 题目:Given a nested list of integers, return the sum of all integers in the list weighted by...

    xeblog 评论0 收藏0
  • leetcode 341 Flatten Nested List Iterator 以及其他Iter

    摘要:返回的是表示是否走到了结尾。起到的就是缓存作用,因为调用之后马上就走到下一个了。如果调用,返回用得到和最初的输入相同的做相同的步骤存入不断拆开得到结果。思想就是来自括号,后面也会跟进的专题 Iterator其实就是一个单链表,无法回头看。java里很多数据结构都有这个接口,使用时需要initalize,得到一个iterator. 调用next()返回的是一个object, 指向的是下一...

    chaosx110 评论0 收藏0
  • leetcode341. Flatten Nested List Iterator

    摘要:题目要求假设有一个嵌套形式的数组,要求按照顺序遍历数组中的元素。思路和代码首先可以想到通过深度优先递归的方式将嵌套形式的数组展开为一个无嵌套的列表。 题目要求 Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a lis...

    MartinHan 评论0 收藏0
  • LeetCode 341. Flatten Nested List Iterator

    摘要:设计一个迭代器,使其能够遍历这个整型列表中的所有整数。列表中的项或者为一个整数,或者是另一个列表。示例输入输出解释通过重复调用直到返回,返回的元素的顺序应该是。 Description Given a nested list of integers, implement an iterator to flatten it. Each element is either an integ...

    mingzhong 评论0 收藏0
  • [LintCode/LeetCode] Flatten Nested List Iterator

    摘要:首先,根据迭代器需要不断返回下一个元素,确定用堆栈来做。堆栈初始化数据结构,要先从后向前向堆栈压入中的元素。在调用之前,先要用判断下一个是还是,并进行的操作对要展开并顺序压入对直接返回。 Problem Given a nested list of integers, implement an iterator to flatten it. Each element is either...

    spacewander 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<