C++ solution, O(1) space, easy understanding, with simple comment


  • -2
    L
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        vec1 = v1;
        vec2 = v2;
        flag1 = !vec1.empty();  // if vec1 is empty, end start from vec2
        idx1 = 0;
        idx2 = 0;
    }
    
    int next() {
        int val = 0;
        if (flag1 && idx1 < vec1.size()) {
            val = vec1[idx1++];
            if (idx2 < vec2.size()) flag1 = false; // if vec2 is not end, change the flag1
        } else if (!flag1 && idx2 < vec2.size()) {
            if (idx1 < vec1.size())flag1 = true;   // if vec1 is not end, change the flag1
            val = vec2[idx2++];
        }
        return val;
    }
    
    bool hasNext() {
        return idx1 < vec1.size() || idx2 < vec2.size();
    }
    vector<int> vec1, vec2;
    bool flag1;
    int idx1, idx2 = 0;

  • 0
    L

    Not O(1) space, can't be extended into k vectors case


Log in to reply
 

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