题目描述:
Follow up Zigzag Iterator: What if you are given k
1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous fork > 2
cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".
Example
题目思路:
Given k = 3
1d vectors:
[1,2,3]
[4,5,6,7]
[8,9]
Return [1,4,8,2,5,9,3,6,7]
.
这题从思路上和Zigzag Iterator大致相仿。先用zigzag的顺序遍历一遍整个2d vector,store在一个vector中,在call next()的时候逐一取出就可以了。这里需要注意的是,由于zigzag是上下上下这样遍历,我们得先求出vecs中最长的那个vector,才知道哪里才能terminate这个遍历。
My code(AC = 611ms):
class ZigzagIterator2 {
public:
/**
* @param vecs a list of 1d vectors
*/
vector<int> zigzag_list;
int index;
ZigzagIterator2(vector<vector<int>>& vecs) {
// initialize your data structure here.
index = 0;
// get the vec with max length in the vecs
int max_len = 0;
for (int i = 0; i < vecs.size(); i++) {
max_len = max(max_len, (int)vecs[i].size());
}
// build zigzag_list
int idx = 0;
while (idx < max_len) {
for (int i = 0; i < vecs.size(); i++) {
if (vecs[i].size() > idx) {
zigzag_list.push_back(vecs[i][idx]);
}
}
idx++;
}
}
int next() {
// Write your code here
return zigzag_list[index++];
}
bool hasNext() {
// Write your code here
return index < zigzag_list.size();
}
};
/**
* Your ZigzagIterator2 object will be instantiated and called as such:
* ZigzagIterator2 solution(vecs);
* while (solution.hasNext()) result.push_back(solution.next());
* Ouptut result
*/