C++, simple, O(N) time, O(1) space


  • 0
    C
    class ZigzagIterator {
    public:
    
        int idx = 0;
        vector<int>::iterator curr[2], end[2];
    
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            curr[0] = v1.begin();
            curr[1] = v2.begin();
            end[0] = v1.end();
            end[1] = v2.end();
        }
    
        int next() {
            if (hasNext())
            {
                int val = *(curr[idx]);
                curr[idx]++;
                idx ^= 1;
                return val;
            }
            return INT_MIN;
        }
    
        bool hasNext() {
            if (curr[idx] == end[idx])
                idx ^= 1;
            return curr[idx] != end[idx];
        }
    };

Log in to reply
 

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