2ms c++ iterative solution, no stack, no queue. by ChaoyangHe


  • 1
        int depthSum(vector<NestedInteger>& nestedList) {
            int ret = 0;
            int depth = 1;
            while(!nestedList.empty()){
                vector<NestedInteger> next;
                for(int i = 0; i < nestedList.size(); i++){
                    NestedInteger nl = nestedList[i];
                    if(nl.isInteger()){
                        ret += nl.getInteger() * depth;
                    }else{
                        vector<NestedInteger> nextList = nl.getList();
                        for(int j = 0; j < nextList.size(); j++){
                            next.push_back(nextList[j]);
                        }
                    }
                }
                nestedList = next;
                depth++;
            }
            return ret;
        }
    

Log in to reply
 

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