Two vectors simple C++ way


  • 0
    H

    '''
    class ZigzagIterator {
    private:
    int count = -1;
    int totalSize;
    int shortLen;
    int longVec; // v1/v2 longer one
    vector<int> v1;
    vector<int> v2;
    public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
    this->v1 = v1;
    this->v2 = v2;
    totalSize = v1.size() + v2.size();
    shortLen = min(v1.size(), v2.size());
    longVec = (v1.size()==shortLen) ? 2 : 1;
    }

    int next() {
        int idx = -1;
        int out = 0;
        ++count;
        if (count < 2*shortLen)    // within two vecs
            out = (count % 2) ? v2[count/2] : v1[count/2];
        else {      // in the long vec
            int extra = count - 2*shortLen;
            int idx = shortLen + extra;
            out = (longVec == 1) ? v1[idx] : v2[idx];
        }
        return out;
    }
    
    bool hasNext() {
        return (count < totalSize - 1);
    }
    

    };
    '''


Log in to reply
 

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