lintcode 540 · 左旋右旋迭代器 【算法 中等 迭代器】

题目

https://www.lintcode.com/problem/540

java 复制代码
给你两个一维向量,实现一个迭代器,交替返回两个向量的元素


样例
样例1

输入: v1 = [1, 2] 和 v2 = [3, 4, 5, 6]
输出: [1, 3, 2, 4, 5, 6]
解释:
一开始轮换遍历两个数组,当v1数组遍历完后,就只遍历v2数组了,所以返回结果:[1, 3, 2, 4, 5, 6]
样例2

输入: v1 = [1, 1, 1, 1] 和 v2 = [3, 4, 5, 6]
输出: [1, 3, 1, 4, 1, 5, 1, 6]

参考代码

java 复制代码
public class ZigzagIterator {
     List<Integer> ll1,ll2;
        //len1,len2: 分别表示ll1,ll2的长度 curll:表示当前访问哪个list
        //i:表示即将访问ll1的哪个位置  j:表示即将访问ll2的哪个位置
        int len1=0,len2 =0,curll = 1,i=0,j=0;
       public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
           ll1 =v1;
           ll2=v2;
           len1 = v1.size();
           len2= v2.size();
        }


        public int next() {
           if(curll ==1 && i<len1){
               if(j<len2) curll =2;
               return ll1.get(i++);
           }else{
               if(i<len1) curll =1;
               return ll2.get(j++);
           }
        }


        public boolean hasNext() {
           return i<len1 || j<len2;
        }
}

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator solution = new ZigzagIterator(v1, v2);
 * while (solution.hasNext()) result.add(solution.next());
 * Output result
 */
相关推荐
科大饭桶8 分钟前
数据结构自学Day5--链表知识总结
数据结构·算法·leetcode·链表·c
我爱C编程2 小时前
基于Qlearning强化学习的1DoF机械臂运动控制系统matlab仿真
算法
chao_7892 小时前
CSS表达式——下篇【selenium】
css·python·selenium·算法
chao_7892 小时前
Selenium 自动化实战技巧【selenium】
自动化测试·selenium·算法·自动化
YuTaoShao2 小时前
【LeetCode 热题 100】24. 两两交换链表中的节点——(解法一)迭代+哨兵
java·算法·leetcode·链表
怀旧,2 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
泛舟起晶浪2 小时前
相对成功与相对失败--dp
算法·动态规划·图论
地平线开发者3 小时前
地平线走进武汉理工,共建智能驾驶繁荣生态
算法·自动驾驶
IRevers4 小时前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶
前端拿破轮4 小时前
翻转字符串里的单词,难点不是翻转,而是正则表达式?💩💩💩
算法·leetcode·面试