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 for k > 2
cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".
Example
Example1
Input: k = 3
vecs = [
[1,2,3],
[4,5,6,7],
[8,9],
]
Output: [1,4,8,2,5,9,3,6,7]
Example2
Input: k = 3
vecs = [
[1,1,1]
[2,2,2]
[3,3,3]
]
Output: [1,2,3,1,2,3,1,2,3]
分析
这道题是ZigZag Iterator的扩展,针对了多个数组进行输出。遍历vector需要使用vector<int>::iterator,如何判断遍历是否走到头需要知道vector<int>::end(),所以我们采用两个vector<vector<int>::iterator>记录每一个子数组当前的指针和尾部。使用index记录当前需要遍历的子数组,使用size记录子数组的个数。
Code
class ZigzagIterator2 {
public:
/*
* @param vecs: a list of 1d vectors
*/ZigzagIterator2(vector<vector<int>>& vecs) {
// do intialization if necessary
for (int i = 0; i < vecs.size(); i ++)
{
it.push_back(vecs[i].begin());
end.push_back(vecs[i].end());
}
index = 0;
size = vecs.size();
}
/*
* @return: An integer
*/
int next() {
// write your code here
int tmp = *(it[index%size]);
it[index%size] ++;
index ++;
return tmp;
}
/*
* @return: True if has next
*/
bool hasNext() {
// write your code here
for (int i = 0; i < size; i ++)
{
if (it[index%size] != end[index%size])
return true;
index ++;
}
return false;
}
private:
vector<vector<int>::iterator> it;
vector<vector<int>::iterator> end;
int index;
int size;
};
/**
* Your ZigzagIterator2 object will be instantiated and called as such:
* ZigzagIterator2 solution(vecs);
* while (solution.hasNext()) result.push_back(solution.next());
* Ouptut result
*/
运行效率
Your submission beats 44.42% Submissions!