CPP follow up version for k vectors


  • 2
    class ZigzagIterator {
        vector<vector<int>::iterator> iters;
        vector<vector<int>::iterator> ends;
        int k;
        int flag;
        
    public:
        ZigzagIterator(vector<vector<int>>& vk) {
            k = (int) vk.size();
            iters.resize(k);
            ends.resize(k);
            for (int i = 0; i < k; i++) {
                iters[i] = vk[i].begin();
                ends[i] = vk[i].end();
            }
            flag = 0;
        }
        
        int next() {
            int index;
            while (true){
                if (iters[flag] != ends[flag]) {
                    index = flag;
                    break;
                }
                flag++;
                flag = flag % k;
            }
            flag++;
            flag = flag % k;
            return *iters[index]++;
        }
        
        bool hasNext() {
            for (int i = 0; i < k; i++) {
                if (iters[i] != ends[i])
                    return true;
            }
            return false;
        }
    };
    

Log in to reply
 

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