[LeetCode] Zigzag Iterator

简介: Problem Description: Given two 1d vectors, implement an iterator to return their elements alternately.

Problem Description:

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?


Update: when k vectors are provided, what the results should be still remain to be a question (you may refer to this post). So the following notes do not focus on that now.


The idea is as follows: keep the two beginning iterators and the two end iterators of v1 and v2into two arrays of type vector<int>::iterator with size 2. Then we keep a variable p(initialized to be 0) to record which iterator should be used: p takes values ranging from 0 to1. Each time we call next, update p by p = (p + 1) % 2 to circulate it to point to the next vector.

The code is as follows.

 1 class ZigzagIterator {
 2 public:
 3     ZigzagIterator(vector<int>& v1, vector<int>& v2) {
 4         bs[0] = v1.begin(), bs[1] = v2.begin();
 5         es[0] = v1.end(), es[1] = v2.end();
 6         p = 0;
 7     }
 8 
 9     int next() {
10         int elem;
11         if (bs[0] == es[0]) elem = *bs[1]++;
12         else if (bs[1] == es[1]) elem = *bs[0]++;
13         else {
14             elem = *bs[p]++;
15             p = (p + 1) % 2;
16         }
17         return elem;
18     }
19 
20     bool hasNext() {
21         return bs[0] != es[0] || bs[1] != es[1];
22     }
23 private:
24     int p;
25     vector<int>::iterator bs[2], es[2];
26 };

 

目录
相关文章
LeetCode 341. Flatten Nested List Iterator
给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。
68 0
LeetCode 341. Flatten Nested List Iterator
|
存储
LeetCode 284. Peeking Iterator
给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
83 0
LeetCode 284. Peeking Iterator
|
Python
LeetCode 103. BTree Zigzag Level Order Traversal
给定二叉树,返回其节点值的Z字形级别遍历。 (即,从左到右,然后从右到左进行下一级别并在之间交替)。
71 0
LeetCode 103. BTree Zigzag Level Order Traversal
|
机器学习/深度学习 Perl