展开二维向量
双指针法
- Runtime: 128 ms, faster than 57.63%
- Memory Usage: 50.4 MB, less than 40.68%
- 时间复杂度 O(v/n),空间复杂度O(1)
/**
* @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()
*/
网友评论