JavaScript Solution, just combine vectors at beginning


  • 0
    S

    You can convert the arguments object into an array at the beginning which trivially solves for the general case. The idea here is just to convert k vectors into a one-dimensional array at the beginning.

    function ZigzagIterator(v1, v2) {
      const arrays = [...arguments];
    
      this.index = -1;
      this.lastIndex = arrays.reduce((acc, item) => acc + item.length, 0) - 1;
    
      this.values = [];
    
      let index = 0;
      while (this.lastIndex > this.values.length - 1) {
        for (let array of arrays) {
          if (index <= array.length - 1) {
            this.values.push(array[index]);
          }
        }
        index++;
      }
    }
    
    ZigzagIterator.prototype.hasNext = function hasNext() {
      return this.index < this.lastIndex;
    };
    
    ZigzagIterator.prototype.next = function next() {
      if (!this.hasNext()) {
        return null;
      }
    
      return this.values[++this.index];
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.