标签:lis matrix note data which its with integer ssi
In MATLAB, there is a very useful function called ‘reshape‘, which can reshape a matrix into a new one with different size but keep its original data.
You‘re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and columnnumber of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the ‘reshape‘ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
1 public class Solution { 2 public int[][] matrixReshape(int[][] nums, int r, int c) { 3 int m = nums.length, n = nums[0].length; 4 if (m * n != r * c) return nums; 5 6 int[][] result = new int[r][c]; 7 int rc = 0, cc = 0; 8 for (int i = 0; i < m; i ++) { 9 for (int j = 0; j < n; j++) { 10 result[rc][cc++] = nums[i][j]; 11 if (cc == c) { 12 cc = 0; 13 rc++; 14 } 15 } 16 } 17 return result; 18 } 19 }
标签:lis matrix note data which its with integer ssi
原文地址:http://www.cnblogs.com/amazingzoe/p/6830659.html