Same Logic of Nested List Weight Sum + Hashmap


  • 0
    K

    Using the same approach as Nested List Weight Sum along with a hashmap.

    public class Solution {
        HashMap<Integer, Integer> map = new HashMap<>();
        public int depthSumInverse(List<NestedInteger> nestedList) {
            depthSumInverse(nestedList, 1, 0);
            int finalSum = 0;
            for (int i=map.size(), j=1; i>0; i--, j++) {
                finalSum += map.get(i) * j;
            }
            return finalSum;
        }
        void depthSumInverse(List<NestedInteger> nestedList, int depth, int sum) {
            sum=0;
            for (NestedInteger n : nestedList) {
                if (n.isInteger()) {
                    sum += n.getInteger();
                } else {
                    depthSumInverse(n.getList(), depth+1, sum);
                }
            }
            if (!map.containsKey(depth)) {
                map.put(depth, sum);
            } else {
                map.put(depth, map.get(depth)+sum);
            }        
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.