251. Flatten 2D Vector

2021-11-18  本文已影响0人  jluemmmm

展开二维向量

双指针法

/**
 * @param {number[][]} vec
 */
var Vector2D = function(vec) {
  this.vector = vec;
  this.inner = 0;
  this.outer = 0;
};

/**
 * @return {number}
 */
Vector2D.prototype.next = function() {
  if (this.hasNext()) {
    return this.vector[this.outer][this.inner++];
  }
  
};

/**
 * @return {boolean}
 */
Vector2D.prototype.hasNext = function() {
  while (this.outer < this.vector.length && this.inner === this.vector[this.outer].length) {
    this.inner = 0;
    this.outer++;
  }
  return this.outer < this.vector.length;
};

/** 
 * Your Vector2D object will be instantiated and called as such:
 * var obj = new Vector2D(vec)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */
上一篇 下一篇

猜你喜欢

热点阅读