Strange behavior of my solution (c++)


  • 0
    X

    Please see my C++ solution below. It passed the OJ. However, when I changed the code line

    vector<NestedInteger> &tmp = a->getList();
    

    to

    vector<NestedInteger> tmp(a->getList());
    

    it will not give the correct solution (it will output 6 for the first case).

    class Solution {
    public:
        int depthSum(vector<NestedInteger>& nestedList) {
          int res = 0, depth = 0;
          queue<NestedInteger*> q;
          for (auto &value: nestedList) {
              q.push(&value);
          }
          while (!q.empty()) {
            int q_len = q.size();
            // cout << q_len << endl;
            depth++;
            for (int i = 0; i < q_len; ++i) {
              NestedInteger *a = q.front();
              q.pop();
              if (!a->isInteger()) {
                  vector<NestedInteger> &tmp = a->getList();
                  for (auto & value: tmp) {
                      q.push(&value);
                  }
              }
              else {
                  //cout << a->getInteger();
                res += depth * a->getInteger();
              }
            }
          }
            return res;
    
        }
    };
    

Log in to reply
 

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