284. Peeking Iterator

Leetcode link

解题思路

题目要求我们实现一个可以 peekPeekingIterator。通过继承了一个 Iterator,我们可以使用它的 nexthasNext 方法。

为此我们可以用两个变量 nextNumhasNextNum 分别记录当前的对象状态。

这样子 peekhasNext 方法只要直接返回变量即可。

在构造函数与 next 方法中,我们只需要对这两个变量进行单独维护就好。

C++

class PeekingIterator : public Iterator {
 private:
  int nextNum;
  bool hasNextNum;

 public:
  PeekingIterator(const vector<int>& nums) : Iterator(nums) {
    hasNextNum = Iterator::hasNext();
    if (hasNextNum) {
      nextNum = Iterator::next();
    }
  }

  // Returns the next element in the iteration without advancing the iterator.
  int peek() { return nextNum; }

  // hasNext() and next() should behave the same as in the Iterator interface.
  // Override them if needed.
  int next() {
    // preserve current result
    int res = nextNum;

    hasNextNum = Iterator::hasNext();
    if (hasNextNum) {
      nextNum = Iterator::next();
    }

    return res;
  }

  bool hasNext() const { return hasNextNum; }
};

Javascript

var PeekingIterator = function(iterator) {
    this.hasNextNum = iterator.hasNext();
    if(this.hasNextNum) {
        this.nextNum = iterator.next();
    }
  // 保存起来之后 next 需要用到
    this.iterator = iterator;
};

/**
 * @return {number}
 */
PeekingIterator.prototype.peek = function() {
    return this.nextNum;
};

/**
 * @return {number}
 */
PeekingIterator.prototype.next = function() {
    let res = this.nextNum;

    this.hasNextNum = this.iterator.hasNext();
    if(this.hasNextNum) {
        this.nextNum = this.iterator.next();
    }

    return res;
};

/**
 * @return {boolean}
 */
PeekingIterator.prototype.hasNext = function() {
    return this.hasNextNum;
};

results matching ""

    No results matching ""