码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Zigzag Iterator

时间:2015-09-14 13:57:49      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode] Zigzag Iterator

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4806896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!