C++ solution using move semantics to eliminate extra copying.


  • 0
    G
    class ZigzagIterator {
    
        typedef vector<int>::iterator Iter;    
        vector<int> V1;
        vector<int> V2;
        Iter Is[2];
        int Idx;
        
    public:
        
        
        ZigzagIterator(vector<int>& v1, vector<int>& v2)
        :
        V1(std::move(v1)),
        V2(std::move(v2)),
        Idx(0)
        {
            Is[0] = V1.begin();
            Is[1] = V2.begin();
        }
       
        int next() 
        {
            if((Idx == 0 &&Is[Idx] == V1.end())||
               (Idx == 1 && Is[Idx] == V2.end()))
            {
                Idx = 1 - Idx;
            }
            
            int Res = *(Is[Idx]);
            
            Is[Idx]++;
            Idx = 1 - Idx;
            return (Res);
        }
    
        bool hasNext() 
        {
            return (Is[0] != V1.end() || Is[1] != V2.end());
        }
    };

Log in to reply
 

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