easy AC cpp solution for k vectors, no k iterators


  • 0
    M
    class ZigzagIterator {
      int cycle;
      int cnt;
      int col;
    
      vector<vector<int>> table;
      
    public:
      ZigzagIterator(vector<int>& v1, vector<int>& v2):cnt(0), cycle(2) {
        table.push_back(v1);
        table.push_back(v2);
        col = max(v1.size(), v2.size());
      }
      
      int next() {
        int tmp = table[cnt % cycle][cnt / cycle];
        cnt++;
        return tmp;
      }
      
      bool hasNext() {
        while (table[cnt % cycle].size() <= cnt / cycle && cnt < cycle * col) {
          cnt++;
        }
        if (cnt >= cycle * col) {
          return false;
        }
        return true;
      }
    };
    

Log in to reply
 

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