C++, Using Queue, extend to K-vector, O(K) space


  • 0
    class ZigzagIterator {
    
        queue<pair<vector<int>::iterator,vector<int>::iterator>> m_que;
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
           if(v1.size() != 0)
                m_que.emplace(v1.begin(),v1.end());
            if(v2.size() != 0)
                m_que.emplace(v2.begin(),v2.end());
           
        }
    
        int next() {
            auto p = m_que.front();
            m_que.pop();
            int res = *p.first;
            if(++p.first != p.second)
                m_que.push(p);
            return res; 
        }
    
        bool hasNext() {
            return !m_que.empty();
           
        }
    };
    

Log in to reply
 

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