zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode] Peeking Iterator

LeetCode Iterator
2023-09-14 09:01:04 时间
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 wi

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().

Here is an example. Assume that the iterator is initialized to the beginning of the list: [1, 2, 3].

Call next() gets you 1, the first element in the list.

Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.

You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false.

Hint:


Think of “looking ahead”. You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google’s guava library source code.

用一个变量来保存peek元素值,每次调用next()和peek()时更新其值。

Java:


//Java Iterator interface reference: //https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator Integer { Integer peek = null; private Iterator Integer iterator; public PeekingIterator(Iterator Integer iterator) { this.iterator = iterator; // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if (peek == null) { peek = iterator.next(); return peek; // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if (peek == null) { return iterator.next(); else { Integer temp = peek; peek = null; return temp; @Override public boolean hasNext() { if (peek != null) { return true; else { return iterator.hasNext(); }
LeetCode 284. Peeking Iterator 给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
彻底理解 for of 和 Iterator 本文主要来说下ES6的Iterator,目的在于理解它的概念、作用、以及现有的应用,最后学以致用。 Iterator可以说是ES6内相当重大的一个特性,也是很多其他特性运行的基石。 为什么Iterator地位如此之高呢?
每天一个知识点(九)你知道迭代器 Iterator 是什么吗? 迭代器模式是二十三种设计模式之一,这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 在Java中,通过iterator.hasNext()检测是否存在下一条记录,通过iterator.next遍历集合中的元素。
Collection集合框架与Iterator迭代器 集合框架 集合Collection概述 集合是Java中提供的一种容器,可以用来存储多个数据 集合与数组的区别: 数组的长度固定,集合的长度可变 数组中存储的是同一类型的元素,可以存储基本数据类型值,集合存储的都是对象。而且对象类型可以不一致。开发中一般当对象多的时候,使用集合进行存储 Colle