Simple C++ solution beats 90% and is O(1) in space.


  • 0
    S

    To extend this solution to k vectors, the onV1 boolean must be substituted with an integer corresponding to the number of vector.

    class ZigzagIterator {
    public:
        vector<int>::iterator it;
        vector<int>::iterator it1;
        vector<int>::iterator it2;
        
        vector<int>::iterator it1_end;
        vector<int>::iterator it2_end;
    
    
        bool onV1;
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            it1 = v1.begin();
            it2 = v2.begin();
            
            it1_end = v1.end();
            it2_end = v2.end();
     
            onV1 = (it1 != it1_end);
        }
    
        int next() {
            if(onV1){
                int temp = (*it1);
                ++it1;
                if (it2 != it2_end) onV1 = false;
                return (temp);
            } else {
                int temp = (*it2);
                ++it2;
                if (it1 != it1_end) onV1 = true;
                return (temp);
            }
            return -1;
        }
    
        bool hasNext() {
            bool has_next;
            if(onV1){
                has_next = (it1 != it1_end);
            } else {
                has_next = (it2 != it2_end);
            }
            return has_next;
        }
    };
    
    

Log in to reply
 

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