Given two1dvectors, implement an iterator to return their elements alternately.
Have you met this question in a real interview?
Yes
Example
Given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returnsfalse
, the order of elements returned by next should be:[1, 3, 2, 4, 5, 6]
.
line 8 not bool isV1 ,
line 16 missing ++ , should not return here
line 20 missing negation
class ZigzagIterator {
public:
/**
* @param v1 v2 two 1d vectors
*/
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
// initialize your data structure here.
isV1 = !v1.empty();
begin[0] = v1.begin(), end[0] = v1.end();
begin[1] = v2.begin(), end[1] = v2.end();
}
int next() {
// Write your code here
int res = 0;
if (isV1) {
res = *begin[0]++;
} else {
res = *begin[1]++;
}
isV1 = !isV1;
return res;
}
bool hasNext() {
// Write your code here
if (begin[0] == end[0]) {
isV1 = false;
}
if (begin[1] == end[1]) {
isV1 = true;
}
return begin[0] != end[0] || begin[1] != end[1];
}
private:
vector<int>::iterator begin[2], end[2];
bool isV1;
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator solution(v1, v2);
* while (solution.hasNext()) result.push_back(solution.next());
* Ouptut result
*/