C++ extensible solution (for k vectors)


  • 0
    S
    class ZigzagIterator {
    public:
        ZigzagIterator(vector<int>& v1, vector<int>& v2) {
            if (v1.size() > 0) {
                data.push_back(v1);
            }
            
            if (v2.size() > 0) {
                data.push_back(v2);
            }
            cur_arr_idx = 0;
            idx.assign(data.size(), 0);
        }
    
        int next() {
            int ret = data[cur_arr_idx][idx[cur_arr_idx]];
            idx[cur_arr_idx]++;
            cur_arr_idx = (cur_arr_idx + 1) % data.size();
            
            return ret;
        }
    
        bool hasNext() {
            if (data.empty()) return false;
            
            int prev = cur_arr_idx;
            while (idx[cur_arr_idx] == data[cur_arr_idx].size()) {
                cur_arr_idx = (cur_arr_idx + 1) % data.size();
                if (cur_arr_idx == prev) return false;
            }
            
            return true;
        }
        
    private:
        vector<vector<int>> data;
        int cur_arr_idx;
        vector<int> idx;
    };`

  • 0

    How is it extensible for k vectors?


  • 0
    S

    Currently it is restricted by the constructor: ZigzagIterator(vector<int>& v1, vector<int>& v2)

    If add another constructor

    ZigzagIterator(vector<vector<int>>& v)

    The solution should be able to support k vectors.


  • 0

    But then you'll only cycle, not zigzag.


  • 0
    S

    Zigzag is a circle for k=2 case, right?


Log in to reply
 

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