首页 > 其他分享 >【队列】LeetCode 281. 锯齿迭代器

【队列】LeetCode 281. 锯齿迭代器

时间:2023-01-22 16:56:26浏览次数:50  
标签:hasNext 迭代 public queue add 281 it2 LeetCode

题目链接

281. 锯齿迭代器

思路

使用队列进行保存

代码

public class ZigzagIterator {
    Queue<Iterator<Integer>> queue = new LinkedList<>();

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        Iterator<Integer> it1 = v1.iterator();
        Iterator<Integer> it2 = v2.iterator();
        if(it1.hasNext()){
            queue.add(it1);
        }
        if(it2.hasNext()){
            queue.add(it2);
        }
    }

    public int next() {
        Iterator<Integer> it = queue.poll();
        int v = it.next();
        if(it.hasNext()){
            queue.add(it);
        }
        
        return v;
    }

    public boolean hasNext() {
        return !queue.isEmpty();
    }
}

标签:hasNext,迭代,public,queue,add,281,it2,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17064500.html

相关文章

  • 【队列】LeetCode 346. 数据流中的移动平均值
    题目链接346.数据流中的移动平均值思路队列设计基础题代码classMovingAverage{privateIntegercurrentSum=0;privateQueue<Integer>queue=newLi......
  • 详细实例说明+典型案例实现 对迭代法进行全面分析 | C++
    第四章迭代法:::hljs-center目录第四章迭代法●前言●一、迭代法是什么?1.简要介绍2.代码示例(简单理解)3.生活实例●二、迭代法的典型案例——开平方&帕......
  • [LeetCode] 684. Redundant Connection
    Inthisproblem,atreeisan undirectedgraph thatisconnectedandhasnocycles.Youaregivenagraphthatstartedasatreewith n nodeslabeledfrom......
  • leetcode笔记——328周赛
    1.二维前缀和,二维差分304.二维区域和检索-矩阵不可变-力扣(LeetCode)二维前缀和怎么处理,注意加减的下标 2.2537.统计好子数组的数目-力扣(LeetCode)首先看到子数......
  • 【双指针】LeetCode 409. 最长回文串
    题目链接409.最长回文串思路遍历字符串过程中统计字符出现个数,如果达到2则说明可以放到回文串的两端,需要result+=2。遍历完之后的回文串如果长度小于s,说明s中存......
  • 迭代:求第n个斐波那契数(不考虑溢出)
    斐波那契数列:前两个数之和等于第三个数(如11235813213455......)描述第n个斐波那契数列:由图Fibn<=21n>2Fib(n-1)+Fib(n-2)可知#include<stdio.h>intFib(intn){i......
  • 迭代求n的阶乘
    解法:#include<stdio.h>intFacl(intn){inti=0;intret=1;for(i=1;i<=n;i++){ret*=i;}returnret;}intmain(){intn=0;intret......
  • LeetCode.541 反转字符串II
    1.题目给定一个字符串s和一个整数k,从字符串开头算起,每计数至2k个字符,就反转这2k字符中的前k个字符。如果剩余字符少于k个,则将剩余字符全部反转。如果剩余字符小......
  • LeetCode.面试题02.05-链表求和-题解分析
    题目来源面试题02.05.链表求和题目详情给定两个用链表表示的整数,每个节点包含一个数位。这些数位是反向存放的,也就是个位排在链表首部。编写函数对这两个整数求和,并......
  • [LeetCode] 1824. Minimum Sideway Jumps
    Thereisa 3laneroad oflength n thatconsistsof n+1 points labeledfrom 0 to n.Afrog starts atpoint 0 inthe second lane andwantsto......