281. Zigzag Iterator


Given two 1d vectors, implement an iterator to return their elements alternately.

Example:

Input:
v1 = [1,2]
v2 = [3,4,5,6] 

Output: [1,3,2,4,5,6]

Explanation: 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:

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:

Input:
[1,2,3]
[4,5,6,7]
[8,9]

Output: [1,4,8,2,5,9,3,6,7].

方法1:

思路:

虽然适用于follow up,但这个方法很慢,应该是不必要的拷贝了两次v1,v2的结果。如果选择将k个数组储存成1个vector的形式大概免不了两次拷贝,所以才需要更优化的做法。

先第一次copy形成vector<vector<int>> v, 然后一列一列推进result,某一行不够了就跳过。next(), hasNext()就比较省事。

class ZigzagIterator {
public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        vector<vector<int>> v = {v1, v2};
        int maxLen = max(v1.size(), v2.size());
        
        for (int i = 0; i < maxLen; i++){
            for (auto item: v){
                if (i < item.size()){
                    result.push_back(item[i]);
                }
            }
        }
        it = result.begin();
    }

    int next() {
        return *it++;
    }

    bool hasNext() {
        if (it == result.end())
            return false;
        return true;
    }
private:
    vector<int> result;
    vector<int>::iterator it;
};

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i(v1, v2);
 * while (i.hasNext()) cout << i.next();
 */

方法2: queue + iterator

Discussion: https://leetcode.com/problems/zigzag-iterator/discuss/71835/C%2B%2B-with-queue-(compatible-with-k-vectors)

思路:

基本不用拷贝vectors本身,只需要将每个vector的iterator依次推进一个队列,在next()的时候pop出来队首的iterator,提取,如果还有下一个元素,iter + 1继续入队等待。那么这个时候就发现需要随时判断是否已经到了v.end(),所以队列的形式需要一个pair,存储一对iterator,方便随时判断。

易错点

  1. q的形式
  2. 查iter == end()
class ZigzagIterator {
public:
    ZigzagIterator(vector<int>& v1, vector<int>& v2) {
        if (!v1.empty()) q.push(make_pair(v1.begin(), v1.end()));
        if (!v2.empty()) q.push(make_pair(v2.begin(), v2.end()));
    }

    int next() {
        auto its = q.front();
        q.pop();
        int result = *(its.first);
        if ((its.first + 1) != its.second){
            q.push(make_pair(its.first + 1, its.second));
        }
        return result;
    }

    bool hasNext() {
        return !q.empty();
    }
private:
    queue<pair<vector<int>::iterator,vector<int>::iterator>> q;
};

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i(v1, v2);
 * while (i.hasNext()) cout << i.next();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值