566. Reshape the Matrix 簡單但是實用的 以 ? 數為一組

像是假設有67個資料你要分成每8個一組的方式

題目是這樣的

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.

以下是簡潔的寫法!!

public int[][] matrixReshape(int[][] nums, int r, int c) {
int n = nums.length, m = nums[0].length;
if (r*c != n*m) return nums;
int[][] res = new int[r][c];
for (int i=0;i<r*c;i++)
res[i/c][i%c] = nums[i/m][i%m];
return res;
}

另外講一個如果要不斷循環某個數(這算是在看作業系統的 講義的時候看到的用法)

例如 0 > 1 > 2 >0 >1 >2…

只要 i%3 就好了!

同理可類推 i%4 就是 0 1 2 3 之類的

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.