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].
思路:
1. 刚开始想到用两个计数器来做。例如,
[1,2,3]
[4,5,6,7]
[8,9]
用totalCount表示对应的输出位置,arrNum表示输出数据来源的数组:
| totalCount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| arrNum | 0 | 1 | 2 | 0 | 1 | 2 | 0 | 1 | 2 | 0 | 1 |
(totalCount-arrNum)/3可以得到arrNum中的index。例如,totalCount=6,则(6-0)/3=2就是第0个array中第2个index;当计算得到的index超过该array的最大坐标,则往后再计数,直到所取数据在最大坐标范围以内。例如,totalCount=9,则(9-0)/3=3就是第0个array中第3个index,但是第0个array最大index=2,所以不能取。
2. 这个方法的最大问题是,由于每个array长度不等,所以可能需要不停的跳过多个没有数据的位置,作了很多无用的判断。最好的解决方法是,每个array一旦取完最后一个数,就从待考虑的pool里面kick out!参考了http://www.cnblogs.com/grandyang/p/5212785.html 把每个array的首尾iterator(指针)放到queue里,然后顺序取出,每次取出时都把首iterator加1,看是否是最后一个位置,如果是,则不再重新push到queue里; 如果不是,则继续push到queue
3. 体会一下,为什么用queue?
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if(!v1.empty()) qq.push(make_pair(v1.begin(),v1.end()));
if(!v2.empty()) qq.push(make_pair(v2.begin(),v2.end()));
}
int next() {
auto left=qq.front().first,right=qq.front().second;
qq.pop();
if(left+1!=right)
qq.push(make_pair(left+1,right));
return *left;
}
bool hasNext() {
return !qq.empty();
}
private:
queue<pair<vector<int>::iterator,vector<int>::iterator>> qq;
};
本文介绍了一种实现交错迭代多个一维向量的方法。通过使用队列来管理各个向量的迭代器,确保能够按顺序交替返回元素。适用于不同长度的向量,并提供了高效的解决方案。
957

被折叠的 条评论
为什么被折叠?



