281. Zigzag Iterator
Given two 1d vectors, implement an iterator to return their elements alternately.
Example:
Input:
v1 = [1,2]
v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,3,2,4,5,6].
Follow up:
What if you are given k 1d vectors? How well can your code be extended to such cases?
Clarification for the follow up question:
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”. For example:
Input:
[1,2,3]
[4,5,6,7]
[8,9]
Output: [1,4,8,2,5,9,3,6,7].
方法1:
思路:
虽然适用于follow up,但这个方法很慢,应该是不必要的拷贝了两次v1,v2的结果。如果选择将k个数组储存成1个vector的形式大概免不了两次拷贝,所以才需要更优化的做法。
先第一次copy形成vector<vector<int>> v, 然后一列一列推进result,某一行不够了就跳过。next(), hasNext()就比较省事。
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
vector<vector<int>> v = {v1, v2};
int maxLen = max(v1.size(), v2.size());
for (int i = 0; i < maxLen; i++){
for (auto item: v){
if (i < item.size()){
result.push_back(item[i]);
}
}
}
it = result.begin();
}
int next() {
return *it++;
}
bool hasNext() {
if (it == result.end())
return false;
return true;
}
private:
vector<int> result;
vector<int>::iterator it;
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/
方法2: queue + iterator
Discussion: https://leetcode.com/problems/zigzag-iterator/discuss/71835/C%2B%2B-with-queue-(compatible-with-k-vectors)
思路:
基本不用拷贝vectors本身,只需要将每个vector的iterator依次推进一个队列,在next()的时候pop出来队首的iterator,提取,如果还有下一个元素,iter + 1继续入队等待。那么这个时候就发现需要随时判断是否已经到了v.end(),所以队列的形式需要一个pair,存储一对iterator,方便随时判断。
易错点
- q的形式
- 查iter == end()
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if (!v1.empty()) q.push(make_pair(v1.begin(), v1.end()));
if (!v2.empty()) q.push(make_pair(v2.begin(), v2.end()));
}
int next() {
auto its = q.front();
q.pop();
int result = *(its.first);
if ((its.first + 1) != its.second){
q.push(make_pair(its.first + 1, its.second));
}
return result;
}
bool hasNext() {
return !q.empty();
}
private:
queue<pair<vector<int>::iterator,vector<int>::iterator>> q;
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/