C++ O(1) space & time complexity solution


  • 0
    B
    class ZigzagIterator {
        vector<int>* v[2];
        int pos;
        
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            v[0] = &v1;
            v[1] = &v2;
            pos = 0;
        }
    
        int next() {
            int i = pos++;
            return (*v[i & 1])[i / 2];
        }
    
        bool hasNext() {
            if (pos / 2 >= (int)v[pos & 1]->size())
                pos++;
            return (pos / 2 < (int)v[pos & 1]->size());
        }
    };
    

Log in to reply
 

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