Easy to extend to K vectors using queue


  • -1
    K
    class ZigzagIterator {
    public:
    vector<vector<int>> vecs;
    queue<pair<vector<int>::iterator, vector<int>::iterator>> iters;
    
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        vecs.push_back(v1);
        vecs.push_back(v2);
        int sz = static_cast<int>(vecs.size());
        for (int i = 0; i < sz; i++) {
            if (!vecs[i].empty())
                iters.emplace(vecs[i].begin(), vecs[i].end());
        }
    } 
    
    int next() { 
        auto i = iters.front();
        iters.pop();
        int v = *(i.first);
        if (++(i.first) != i.second)
            iters.push(i);
        return v;
    } 
    
    bool hasNext() { 
        return !iters.empty();
    } 
    };

  • 0

    How would you extend it to K vectors?

    Also, your code is strange. Why copy the vectors and then use iterators of your copies instead of just using iterators of the originals?


Log in to reply
 

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