#541 Zigzag Iterator II

题目描述:

Follow up Zigzag Iterator: What if you are given k 1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous fork > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".

Example

Given k = 3 1d vectors:

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

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

题目思路:

这题从思路上和Zigzag Iterator大致相仿。先用zigzag的顺序遍历一遍整个2d vector,store在一个vector中,在call next()的时候逐一取出就可以了。这里需要注意的是,由于zigzag是上下上下这样遍历,我们得先求出vecs中最长的那个vector,才知道哪里才能terminate这个遍历。

My code(AC = 611ms):

class ZigzagIterator2 {
public:
    /**
     * @param vecs a list of 1d vectors
     */
    vector<int> zigzag_list;
    int index;
     
    ZigzagIterator2(vector<vector<int>>& vecs) {
        // initialize your data structure here.
        index = 0;
        
        // get the vec with max length in the vecs
        int max_len = 0;
        for (int i = 0; i < vecs.size(); i++) {
            max_len = max(max_len, (int)vecs[i].size());
        }
        
        // build zigzag_list
        int idx = 0;
        while (idx < max_len) {
            for (int i = 0; i < vecs.size(); i++) {
                if (vecs[i].size() > idx) {
                    zigzag_list.push_back(vecs[i][idx]);
                }
                
            }
            idx++;
        }
    }

    int next() {
        // Write your code here
        return zigzag_list[index++];
    }

    bool hasNext() {
        // Write your code here
        return index < zigzag_list.size();
    }
};

/**
 * Your ZigzagIterator2 object will be instantiated and called as such:
 * ZigzagIterator2 solution(vecs);
 * while (solution.hasNext()) result.push_back(solution.next());
 * Ouptut result
 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值