#540 Zigzag Iterator

题目描述:

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
 */


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值