zoukankan      html  css  js  c++  java
  • [LeetCode] Zigzag Iterator

    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?

    后天Onsite,求人品,求Offer! ( T,T

     1 class ZigzagIterator {
     2 private:
     3     vector<int> &mv1, &mv2;
     4     vector<int>::iterator it1, it2, it;
     5 public:
     6     ZigzagIterator(vector<int>& v1, vector<int>& v2) : mv1(v1), mv2(v2) {
     7         it1 = v1.begin();
     8         it2 = v2.begin();
     9         it = (it1 == mv1.end()) ? it2 : it1;
    10     }
    11 
    12     int next() {
    13         int val = *it;
    14         if (it == it1) {
    15             ++it1;
    16             it = (it2 == mv2.end()) ? it1 : it2;
    17         } else {
    18             ++it2;
    19             it = (it1 == mv1.end()) ? it2 : it1;
    20         }
    21         return val;
    22     }
    23 
    24     bool hasNext() {
    25         return it1 != mv1.end() || it2 != mv2.end();
    26     }
    27 };
    28 
    29 /**
    30  * Your ZigzagIterator object will be instantiated and called as such:
    31  * ZigzagIterator i(v1, v2);
    32  * while (i.hasNext()) cout << i.next();
    33  */
  • 相关阅读:
    [Apio2014]回文串
    省队集训day6 C
    省队集训day6 B
    省队集训Day3 light
    省队集训Day3 tree
    多串匹配
    ubuntu卸载福昕阅读器
    greenlet
    python multithread task_done
    mysql参数调优
  • 原文地址:https://www.cnblogs.com/easonliu/p/4806896.html
Copyright © 2011-2022 走看看