Follow upZigzag Iterator: What if you are givenk1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous fork > 2cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".

Have you met this question in a real interview?

Yes

Example

Givenk = 31d vectors:

[1,2,3]
[4,5,6,7]
[8,9]

Return[1,4,8,2,5,9,3,6,7].

line 11 , use push back instead of resize
line 40 variable name problem cur instead of next same as function name

class ZigzagIterator2 {
public:
    /**
     * @param vecs a list of 1d vectors
     */
    ZigzagIterator2(vector<vector<int>>& vecs) {
        // initialize your data structure here.
        k = vecs.size();
        cur = 0;
        for (auto& arr : vecs) {
            begin.push_back(arr.begin());
            end.push_back(arr.end());
        }
    }

    int next() {
        // Write your code here
        int res = *begin[cur]++;
        cur = (cur + 1) % k;
        return res;
    }

    bool hasNext() {
        // Write your code here
        bool ans = false;
        int size = 0;
        while (begin[cur] == end[cur]) {
            cur = (cur + 1) % k;
            ++size;
            if (size == k) {
                break;
            }
        }
        if (size < k) {
            ans = true;
        }
        return ans;
    }

    int cur;
    int k;
    vector<vector<int>::iterator> begin, end;
};

/**
 * Your ZigzagIterator2 object will be instantiated and called as such:
 * ZigzagIterator2 solution(vecs);
 * while (solution.hasNext()) result.push_back(solution.next());
 * Ouptut result
 */

results matching ""

    No results matching ""