LeetCode 271. Zigzag Iterator

本文介绍了一种实现交错迭代多个一维向量的方法。通过使用队列来管理各个向量的迭代器,确保能够按顺序交替返回元素。适用于不同长度的向量,并提供了高效的解决方案。

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表示输出数据来源的数组:

totalCount012345678910
arrNum01201201201

(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;
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值