Last active
May 13, 2017 13:27
-
-
Save Linkding/725f77ddd3c27d84a96aec24a93ae5a8 to your computer and use it in GitHub Desktop.
566_Reshape_the_Matrix.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} nums | |
* @param {number} r | |
* @param {number} c | |
* @return {number[][]} | |
*/ | |
var matrixReshape = function(nums, r, c) | |
{ | |
var len = nums.length | |
var element_num = nums[0].length | |
//console.log(element_num) | |
if (element_num * len == r * c) | |
{ | |
/*整合成一个数组; | |
将nums的所有元素都拼进第一元素*/ | |
var a1 = nums[0] | |
for (j = 1; j < len; j++) | |
{ | |
for (i = 0; i < element_num; i++) | |
{ | |
a1.push(nums[j][i]) | |
} | |
} | |
console.log(a1) | |
/*for循环 c 次 | |
每次取数组r个值,取值完删除*/ | |
var res = [] | |
for (f = 0; f < r ; f++) | |
{ | |
var a2 = [] | |
for (l = 0; l < c; l++) | |
{ | |
a2.push(a1[l]) | |
} | |
res.push(a2) | |
if (c != 1){ | |
a1.splice(0,c) | |
} | |
else{ | |
a1.splice(0,1) | |
} | |
//console.log(a1) | |
} | |
return res | |
//console.log(a1) | |
} | |
else | |
{ | |
return nums | |
} | |
}; | |
console.log(matrixReshape([[1,2],[3,4]], 4, 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment