Given two 1d vectors, implement an iterator to return their elements alternately.

Example:

Input:
v1 = [1,2]
v2 = [3,4,5,6] Output: [1,3,2,4,5,6] Explanation: 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?

Clarification for the follow up question:
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example:

Input:
[1,2,3]
[4,5,6,7]
[8,9] Output: [1,4,8,2,5,9,3,6,7].

这道题让我们写一个之字形迭代器,跟之前那道 Flatten 2D Vector 有些类似,那道题是横向打印,这道题是纵向打印,虽然方向不同,但是实现思路都是大同小异。博主最先想到的方法是用两个变量i和j分别记录两个向量的当前元素位置,初始化为0,然后当 i<=j 时,则说明需要打印 v1 数组的元素,反之则打印 v2 数组中的元素。在 hasNext 函数中,当i或j打印等于对应数组的长度时,将其赋为一个特大值,这样不影响打印另一个数组的值,只有当i和j都超过格子数组的长度时,返回 false,参见代码如下:

解法一:

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
v.push_back(v1);
v.push_back(v2);
i = j = ;
}
int next() {
return i <= j ? v[][i++] : v[][j++];
}
bool hasNext() {
if (i >= v[].size()) i = INT_MAX;
if (j >= v[].size()) j = INT_MAX;
return i < v[].size() || j < v[].size();
}
private:
vector<vector<int>> v;
int i, j;
};

下面来看另一种解法,这种解法直接在初始化的时候就两个数组按照之字形的顺序存入另一个一位数组中了,那么就按顺序打印新数组中的值即可,参见代码如下:

解法二:

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
int n1 = v1.size(), n2 = v2.size(), n = max(n1, n2);
for (int i = ; i < n; ++i) {
if (i < n1) v.push_back(v1[i]);
if (i < n2) v.push_back(v2[i]);
}
}
int next() {
return v[i++];
}
bool hasNext() {
return i < v.size();
}
private:
vector<int> v;
int i = ;
};

由于题目中的 Follow up 让将输入换成k个数组的情况,那么上面的解法一就不适用了,解法二的空间复杂度比较高,所以需要一种更高效的方法。这里可以采用 queue 加 iterator 的方法,用一个 queue 里面保存 iterator 的 pair,在初始化的时候,有几个数组就生成几个 pair 放到 queue 中,每个 pair 保存该数组的首位置和尾位置的 iterator,在 next() 函数中,取出 queue 队首的一个 pair,如果当前的 iterator 不等于 end(),将其下一个位置的 iterator 和 end 存入队尾,然后返回当前位置的值。在 hasNext() 函数中,只需要看 queue 是否为空即可,参见代码如下:

解法三:

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if (!v1.empty()) q.push(make_pair(v1.begin(), v1.end()));
if (!v2.empty()) q.push(make_pair(v2.begin(), v2.end()));
}
int next() {
auto it = q.front().first, end = q.front().second;
q.pop();
if (it + != end) q.push(make_pair(it + , end));
return *it;
}
bool hasNext() {
return !q.empty();
}
private:
queue<pair<vector<int>::iterator, vector<int>::iterator>> q;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/281

类似题目:

Flatten 2D Vector

参考资料:

https://leetcode.com/problems/zigzag-iterator/

https://leetcode.com/problems/zigzag-iterator/discuss/71781/Short-Java-O(1)-space

https://leetcode.com/problems/zigzag-iterator/discuss/71779/Simple-Java-solution-for-K-vector

https://leetcode.com/problems/zigzag-iterator/discuss/71835/C%2B%2B-with-queue-(compatible-with-k-vectors)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 281. Zigzag Iterator 之字形迭代器的更多相关文章

  1. [LeetCode] Zigzag Iterator 之字形迭代器

    Given two 1d vectors, implement an iterator to return their elements alternately. For example, given ...

  2. [LeetCode#281] Zigzag Iterator

    Problem: Given two 1d vectors, implement an iterator to return their elements alternately. For examp ...

  3. 281. Zigzag Iterator

    题目: Given two 1d vectors, implement an iterator to return their elements alternately. For example, g ...

  4. 【LeetCode】281. Zigzag Iterator 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 deque 日期 题目地址:https://leetc ...

  5. [LeetCode] 284. Peeking Iterator 瞥一眼迭代器

    Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...

  6. 281. Zigzag Iterator z字型遍历

    [抄题]: Given two 1d vectors, implement an iterator to return their elements alternately. Example: Inp ...

  7. 【LeetCode】ZigZag Conversion(Z 字形变换)

    这道题是LeetCode里的第6道题. 题目要求: 将一个给定字符串根据给定的行数,以从上往下.从左到右进行 Z 字形排列. 比如输入字符串为 "LEETCODEISHIRING" ...

  8. [LeetCode] 6. ZigZag Conversion 之字型转换字符串

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  9. [Locked] Zigzag Iterator

    Zigzag Iterator Given two 1d vectors, implement an iterator to return their elements alternately. Fo ...

随机推荐

  1. 洛谷 P2656 (缩点 + DAG图上DP)

    ### 洛谷 P2656 题目链接 ### 题目大意: 小胖和ZYR要去ESQMS森林采蘑菇. ESQMS森林间有N个小树丛,M条小径,每条小径都是单向的,连接两个小树丛,上面都有一定数量的蘑菇.小胖 ...

  2. pymysql 读取大数据内存卡死的解决方案

    背景:目前表中只有5G(后期持续增长),但是其中一个字段(以下称为detail字段)存了2M(不一定2M,部分为0,平均下来就是2M),字段中存的是一个数组,数组中存N个json数据.这个字段如下: ...

  3. linux不同服务器SSH连接与数据传送

    linux不同服务器通过SSH连接 SCP 命令进行数据传送 1. 安装scp yum install -y openssh-client 2.命令 复制文件(本地>>远程):scp /h ...

  4. linux安装redis步骤

    1.安装gcc  redis是c语言编写的 -- 安装命令 yum install gcc-c++ -- 检查gcc 是否安装 gcc -v 2.下载redis安装包,在root目录下执行 wget ...

  5. C# 中如何深度复制某一个类型(备注:可能有 N 个类型需要复制)的对象?

    如题,针对某一个特定的类型,深度复制,没有那么难,最起码可以手动赋值,但如果要针对 N 多类型深度复制,最简单的方法,是把这个对象序列化成 XML.JSON 或其它可以序列化的载体,然后再将这个载体反 ...

  6. Flink,Storm,SparkStreaming性能对比

    Yahoo 的 Storm 团队曾发表了一篇博客文章 ,并在其中展示了 Storm.Flink 和 Spark Streaming 的性能测试结果.该测试对于业界而言极 具价值,因为它是流处理领域的第 ...

  7. VM1059 bootstrap-table.min.js:7 Uncaught TypeError: Cannot read property 'classes' of undefined

    参考链接:https://blog.csdn.net/liuqianspq/article/details/81868283 1.阳光明媚的下午,我在写CRUD,让数据传到前端的时候,解析的时候报错了 ...

  8. WPF,ComboBox,取汉字首字母,extBoxBase.TextChanged

    1取汉字汉语拼音首字母: private static string GetFirstLetterOfChineseString(string CnChar) { long iCnChar; byte ...

  9. IP 跟踪

    #coding=utf-8import sysimport os import re import urllibimport subprocess def getlocation(ip): resul ...

  10. Python struct与小端存储

    参考链接:https://www.liaoxuefeng.com/wiki/1016959663602400/1017685387246080 在使用Python 实现字符向字节数据类型转换的时候,P ...