My Java Solution using HashMap


  • 0
    G
    public class Solution {
        public int depthSumInverse(List<NestedInteger> nestedList) {
            Map<Integer,Integer> map = new HashMap<>();
            helper(nestedList,1,map);
            int depth = map.size();
            int res = 0;
            for(int key : map.keySet()){
                res += map.get(key)*(depth-key+1);
            }
            return res;
        }
        
        private void helper(List<NestedInteger> nestedList, int level, Map<Integer,Integer> map){
            int sum = 0;
            for(NestedInteger nestedInt : nestedList){
                if (nestedInt.isInteger()){
                    sum += nestedInt.getInteger();
                }
                else helper(nestedInt.getList(),level+1,map);
            }
            
            if(map.containsKey(level)){
                map.put(level,map.get(level) + sum);
            } else {
                map.put(level,sum);
            }
        }
    }
    

Log in to reply
 

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