Problem
Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
v1 = [1, 2] v2 = [3, 4, 5, 6]
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 - Update (2015-09-18):
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, given the following input:
[1,2,3] [4,5,6,7] [8,9]It should return
[1,4,8,2,5,9,3,6,7]
.
Solution
关键是hasNext()如何实现。
大概思路是 用curRow 和 curCol来记录当前位置,curRow从0到K-1, 当curRow到 K时, curCol就加一。
细节是 何时停止?每次curRow 从0 开始时,假设该列为空(assumeEmpty = true),当curRow不断加一时,如果遇到一个有效数字,就将assumeEmpty改为false。
当curRow一直到底而且assumeEmpty还是为空时,那么就说明到底了;否则,curRow清零,curCol 加一,重新调用 hasNext();
class ZigzagIterator {
int K;
int curRow;
int curCol;
bool isEmpty;
vector<vector<int>> matrix;
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
matrix.push_back(v1);
matrix.push_back(v2);
K = 2;
curRow = 0;
curCol = 0;
isEmpty = true;
}
int next() {
return matrix[curRow++][curCol];
}
bool hasNext() {
if(curRow == 0) isEmpty = true;
while(curRow < K) {
if(matrix[curRow].size() > curCol) {
isEmpty = false;
return true;
}
curRow++;
}
if(isEmpty) return false;
curRow = 0;
curCol++;
return hasNext();
}
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/