281. Zigzag Iterator z字型遍历

[抄题]:

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].

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不用写ifv1   if v2.hasnext return true; 直接用temp交换就行了

[英文数据结构或算法,为什么不用别的数据结构或算法]:

不知道初始化要写变量 private Iterator<Integer> i, j, tmp;

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 交换的条件是:i.hasNext(), 别人有下一个才能和你换

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

实现类的题目不能设为public class,否则要改文件名。

 [潜台词] :

 

// package whatever; // don't place package name!


import java.io.*;
import java.util.*;
import java.lang.*;
/*
Input:
v1 = [1,2]
v2 = [3,4,5,6] 

Output: [1,3,2,4,5,6]
*/
class driverFuction {
  public static void main (String[] args) {
    List<Integer> v1 = Arrays.asList(1, 2);
    List<Integer> v2 = Arrays.asList(3, 4, 5, 6);
    ZigzagIterator answer = new ZigzagIterator(v1, v2);
    System.out.println(answer.next());
    System.out.println(answer.next());
    System.out.println(answer.next());
    System.out.println(answer.next());
    System.out.println(answer.next());
  }
}

class ZigzagIterator {
    Iterator<Integer> i, j, temp;
  
    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        i = v1.iterator();
        j = v2.iterator();
    }

    public int next() {
        if (i.hasNext()) {temp = j; j = i; i = temp;}
        return j.next();
    }

    public boolean hasNext() {
        if (i.hasNext() || j.hasNext()) return true;
      return false;
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/9463828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值