1ms java solution beat 99.8%


  • 0
    C

    Similar as others, but reduce multification operations by moving it out of iteration.

    public int depthSum(List<NestedInteger> nestedList) {
        return helper(nestedList, 1);
    }
    
    private int helper(List<NestedInteger> nestedList, int level){
        if(nestedList==null || nestedList.isEmpty()) return 0;
        int sum=0, val=0;
        for(NestedInteger i : nestedList){
            if(i.isInteger()){
                val+=i.getInteger();
            } else{
                sum+=helper(i.getList(), level+1);
            }
        }
        return sum+level*val;
    }

Log in to reply
 

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