Javascript solution O(row*column) time and O(row*column) space complexity. Beats 97% of solutions


  • 0
    H
    var matrixReshape = function(nums, r, c) {
      var m = nums.length;
      var n = nums[0].length;
      if (m*n != r*c){
          return nums;
      }
      var ans = [], k;
    
    //set up empty matrix to return as solution
      for (var i = 0; i < r; i++){
          ans[i] = [];
          for (var j = 0; j < c; j++){
              ans[i][j] = 'undefined';
          }
      }
      
    //assign value to empty matrix
      for (var i =0; i < m; i++){
          for (var j = 0; j < n; j++){
              k = (i * n) + j;
              ans[Math.floor(k/c)][k%c] = nums[i][j];
          }
      }
      return ans;
    

    };


Log in to reply
 

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