284.窥视迭代器
链接:284.窥视迭代器
难度:Medium
标签:设计、数组、迭代器
简介:给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。
题解 1 - javascript
- 编辑时间:2020-04-17
- 执行用时:75ms
- 内存消耗:35MB
- 编程语言:javascript
- 解法介绍:缓存值
class PeekingIterator {
constructor(iterator) {
this.iterator = iterator;
this.cacheNext = iterator.next();
this.cacheHasNext = iterator.hasNext();
}
/**
* @return {number}
*/
peek() {
return this.cacheNext;
}
/**
* @return {number}
*/
next() {
const cache = this.cacheNext;
this.cacheHasNext = this.iterator.hasNext();
this.cacheNext = this.iterator.next();
return cache;
}
/**
* @return {boolean}
*/
hasNext() {
return this.cacheHasNext;
}
}
题解 2 - typescript
- 编辑时间:2021-10-05
- 执行用时:80ms
- 内存消耗:39.4MB
- 编程语言:typescript
- 解法介绍:储存下一个值。
class PeekingIterator {
private nextVal: number;
private nextState: boolean;
constructor(private iterator: Iterator) {
this.next();
}
peek(): number {
return this.nextVal;
}
next(): number {
const ans = this.nextVal;
this.nextState = this.iterator.hasNext();
this.nextVal = this.iterator.next();
return ans;
}
hasNext(): boolean {
return this.nextState;
}
}