Zigzag Iterator
Description
null
Solution(javascript)
/**
* @constructor
* @param {Integer[]} v1
* @param {Integer[]} v1
*/
const ZigzagIterator = function ZigzagIterator(v1, v2) {
this.currentRow = 0
this.columnIndices = [0, 0]
this.used = 0
this.total = v1.length + v2.length
this.matrix = [v1, v2]
}
/**
* @this ZigzagIterator
* @returns {boolean}
*/
ZigzagIterator.prototype.hasNext = function hasNext() {
if (this.used < this.total) {
return true
}
return false
}
/**
* @this ZigzagIterator
* @returns {integer}
*/
ZigzagIterator.prototype.next = function () {
const row = this.currentRow
const column = this.columnIndices[row]
this.currentRow = (this.currentRow + 1) % this.matrix.length
if (column < this.matrix[row].length) {
const value = this.matrix[row][column]
this.used += 1
this.columnIndices[row] += 1
return value
}
return this.next()
}
/**
* Your ZigzagIterator will be called like this:
* var i = new ZigzagIterator(v1, v2), a = [];
* while (i.hasNext()) a.push(i.next());
*/