Leetcode 284. Peeking Iterator (Iterator设计题)

leetcode 284. Peeking Iterator | 284. 顶端迭代器(给 iterator 添加 peek 方法) 题目 https://leetcode.com/problems/peeking-iterator/ 题解 一句话解释题意:标准的 iter 接口不包含 peek 功能,本题希望你能够增加这个功能。 // Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<In 阅读详情
  1. Peeking Iterator
    Medium
    Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.

Implement the PeekingIterator class:

PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator.
int next() Returns the next element in the array and moves the pointer to the next element.
boolean hasNext() Returns true if there are still elements in the array.
int peek() Returns the next element in the array without moving the pointer.
Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.

Example 1:

Input
[“PeekingIterator”, “next”, “peek”, “next”, “next”, “hasNext”]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 2, 2, 3, false]

Explanation
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

Constraints:

1 <= nums.length <= 1000
1 <= nums[i] <= 1000
All the calls to next and peek are valid.
At most 1000 calls will be made to next, hasNext, and peek.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

解法1:peek()的时候把next()的元素save到peekElem,如果peek()过了,peeked=true。
这样,下次next()时,如果peeked = true,直接返回peekElem,peeked=false。否则直接调用Iterator::next()。

/*
 * Below is the interface for Iterator, which is already defined for you.
 * **DO NOT** modify the interface for Iterator.
 *
 *  class Iterator {
 *		struct Data;
 * 		Data* data;
 *  public:
 *		Iterator(const vector<int>& nums);
 * 		Iterator(const Iterator& iter);
 *
 * 		// Returns the next element in the iteration.
 *		int next();
 *
 *		// Returns true if the iteration has more elements.
 *		bool hasNext() const;
 *	};
 */

class PeekingIterator : public Iterator {
public:
	PeekingIterator(const vector<int>& nums) : Iterator(nums) {
	    // Initialize any member here.
	    // **DO NOT** save a copy of nums and manipulate it directly.
	    // You should only use the Iterator interface methods.
  	    peeked = false;
	}
	
    // Returns the next element in the iteration without advancing the iterator.
	int peek() {
        if (!peeked) {
            peekElem = Iterator::next();
            peeked = true;
        }
        return peekElem;
	}
	
	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	int next() {
        int res;
        if (!peeked) {
            res = Iterator::next();
        } else {
            res = peekElem;
            peeked = false;
        }
        return res;
	}
	
	bool hasNext() const {
	    if (!peeked) return Iterator::hasNext();
        return peeked;
	}
private:
    int peekElem;
    bool peeked;
};
ARM CoreLink 系列 5.1.1 -- CI-700 System Address Map 】 所有的CHI 命令都包含一个 Source ID 和 Target ID, 其中 Source ID 可以来自于 RN Node, Target ID 可以来自于HN node或者其他 SN node. 其中 Target ID 是通过 SAM解析传入的地址得到的。对于 CI-700中的所有 RN Node 中的 SAM 多会进行配置,因为RN Node 访问的是整个地址空间,不同的地址空间会有不同的属性(I/O, DRAM),所以会对RN SAM 配置多个不同属性的区域。 阅读详情

相关推荐

【5G演进】4G到5G演进之网络架构与协议栈

4G到5G演进之网络架构与协议栈

Learning makes me happy (0^◇^0) 5548

LeetCode: 284. Peeking Iterator

LeetCode: 284. Peeking Iterator 题目描述 Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially pee...

杨领well的专栏 287

如何点亮一颗sensor

要点亮一个sensor需要从,时钟、sensorI2C,供电,reset脚,mipi的配置几个方面一一确认。 reset脚拉高 给sensor的时钟有没有。(目前用到的常为24MHZ) 供电 查看sensor的数据手册,看有几个电源,用示波器量一下是否为手册规定的电压 比如:DVDD 数字电压: AVDD模拟电压 DOVDD芯片引脚出来的电压等为多少。 sensor的I2C能否抓到 将I2C的口对应上,用示波器量取i2c的波形。 检查有应答并且数据正确。读写地址是否正...

weixin_40787463的博客 3664

力扣424、284(2021/10/5每日一题)

第七十五天 --- 力扣424、284(2021/10/5每日一题)题目一思路k==0特别情况k!=0的一般情况:双指针(滑动窗口)Sum Up:代码题目二思路代码直接按照题意模拟 题目一 力扣:424 思路 k==0特别情况 我们乍一看这题,会一下蒙住,关键问题就是有k的存在,可以替换掉一部分字符,那么替换掉谁,在哪里替换都是问题,所以,干脆,上来咱们先考虑特殊情况,即k=0。那么这个问题就转化成为了,在一个目标串上找一子串,其内部字符必须一致,且子串长度最大。这样就很好想了,我们只需要两个指针,扫描

qq_45678698的博客 210

手把手教你:基于STM32H7自制飞控,如何从零开始移植PX4固件(附避坑指南)

本文详细介绍了如何基于STM32H7自制飞控板并移植PX4固件的完整流程,包括硬件设计、开发环境搭建、关键配置文件移植、驱动开发与适配等关键步骤。特别针对PX4-AutoPilot的移植过程提供了实用技巧和避坑指南,帮助开发者高效完成飞控系统开发。

weixin_30271335的博客 150

gephi生成网络关系图_路网拓扑重建专题 (3) 网络图生成

城市道路网建模在获得基础路网之后,需要考虑道路交通网络的描述与表达问题。网络是将现实世界中的事物及其关系进行适当的抽象,构造成由节点和边按照一定规则组成的形式。一个实体网络可以由有限个“节点”集合与“边”集合构成的图表示,即网络表示为。对于一个由个节点组成的无权复杂网络,该图有邻接矩阵,这里。根据研究对象不同,建模方法主要包括原始法[1]和对偶法[2]两种,见图1,字母a-j为交叉口编号...

weixin_39761195的博客 3509

LeetCode //C - 284. Peeking Iterator

【代码】LeetCode //C - 284. Peeking Iterator。

Made in Code 814

【Proteus仿真】基于74LS148+74LS279+74LS48的四路抢答器

【Proteus仿真】基于74LS148+74LS279+74LS48的四路抢答器

perseverance51博客 8854

leetcode 284. Peeking Iterator

leetcode 284. Peeking Iterator https://leetcode.com/problems/peeking-iterator/ 看了Discuss理解了, 关键是: 在class里面 cache两个variable, next用来store下一个Integer,这样每次peek都只用看next,不用move forward noSuchElement用来store是...

DeveloperKangK的博客 258

Cadence OrCAD Capture 软件自带元件原理图符号库目录与介绍图文视频教程

硬件工程师在开始原理图设计时,应该首先拥有自己的元件原理图符号库。基于Capture进行原理图设计的一个很大的优点就是,软件自带的元件库比较全。本文简单介绍Capture软件自带元件库。

fydar的博客 5584

12、控件使用之录入英文、阿拉伯数字删除增加功能及二维码显示

控件使用之录入英文、阿拉伯数字删除增加功能及二维码显示1、用到的控件2、添加控件2.1、添加【文本录入】控件2.1、添加【文本显示】控件2.1、添加【QR 二维码】控件3、保存工程及生成文件4、下载文件 1、用到的控件   需要用的显示控件为【文本显示】控件和【QR二维码】控件,以及触控控件【文本录入】控件。 2、添加控件 2.1、添加【文本录入】控件   【文本录入】控件也叫【ASCI 文本录入】,是用来录入ASCI 字符,打开 DGUS 软件,点击【触控控件】—【文本录入】,用鼠标框选一个区域,即可在右

嵌入式羊圈 633

Leetcode 284. Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek()operation -- it essentially peek() at the element that will be r

无名山丘,崛起成峰 1271

STM32实战开发(66):STM32图像处理开发教程

随着物联网、人工智能和嵌入式技术的不断发展,图像处理技术在嵌入式系统中的应用越来越广泛。图像处理不仅在视觉识别、安防监控、智能家居等领域中发挥着重要作用,也在工业自动化、医疗成像、无人驾驶等高科技领域中占据重要地位。而STM32凭借其强大的硬件性能和丰富的外设支持,成为了许多图像处理应用的理想平台。

2201_76125393的博客 1453

LeetCode 284. Peeking Iterator

题目链接: https://leetcode.com/problems/peeking-iterator/ Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek()ope

ibingoogle的博客 325

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

[leetcode] 284. Peeking Iterator 解题报告

题目链接: https://leetcode.com/problems/peeking-iterator/ Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek()operati

小榕流光的专栏 1289

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode 284: Peeking Iterator

Peeking Iterator Total Accepted: 2156 Total Submissions: 6859 Difficulty: Medium Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peekin

西施豆腐渣 5083

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

[LeetCode 284] Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be re

coder 进阶的专栏 3290

leetcode 284 Peeking Iterator

题目大意: 继承一个Iterator类,实现对下一个int元素的预览功能,想办法保持迭代器的位置。C++中peek()函数: istream::peek()// Below is the interface for Iterator, which is already defined for you. // **DO NOT** modify the interface for Iterator....

天天烤代码 880

[leetcode-284]Peeking Iterator(java)

问题描述: Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be

中华胡杨的专栏 953

LeetCode 284 Peeking Iterator

题目描述Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be re

Yano_nankai的博客 2868

leetcode [284]Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be retu...

weixin_30267697的博客 75

[LeetCode] 284. Peeking Iterator Java

题目: Given an Iterator class interface with methods:next()andhasNext(), design and implement a PeekingIterator that support thepeek()operation -- it essentially peek() at the element that wi...

AC616288149的博客 169

【leetcode】284. Peeking Iterator

题目: Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation – it essentially peek() at the element that will be returned by the next call to next(). 思路: 把下一个元素值以及其存在状态提

zxc120389574的博客 197

leetcode——284——Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation -- it essentially peek() at the element that will be re

happyxuma1991的博客 276

leetcode(284) Peeking Iterator

原题链接: https://leetcode.com/problems/peeking-iterator/ Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operat

specialshoot的博客 507
上一篇: Leetcode 1670. Design Front Middle Back Queue
下一篇: Leetcode 313: Super Ugly Number (超级丑数)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值