题目描述:
Given two 1d vectors, implement an iterator to return their elements alternately.
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]
.
这题的解法有很多。这里用了最土的方法:先将zigzag遍历完的结果存在一个数组中,每次call next()就调用一个element。空间代价是需要一个数组和一个index(始终指向下一个被call的element)。
My code (AC = 44ms):
class ZigzagIterator {
public:
/**
* @param v1 v2 two 1d vectors
*/
vector<int> zigzag_list; // the list to store the zigzag elements
int index; // the index indicating which element should be called next time
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
// initialize your data structure here.
int l1 = 0, l2 = 0;
index = 0;
while (l1 < v1.size() && l2 < v2.size()) {
zigzag_list.push_back(v1[l1++]);
zigzag_list.push_back(v2[l2++]);
}
while (l1 < v1.size()) {
zigzag_list.push_back(v1[l1++]);
}
while (l2 < v2.size()) {
zigzag_list.push_back(v2[l2++]);
}
}
int next() {
// Write your code here
return zigzag_list[index++];
}
bool hasNext() {
// Write your code here
return index < zigzag_list.size();
}
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator solution(v1, v2);
* while (solution.hasNext()) result.push_back(solution.next());
* Ouptut result
*/