Skip to content

Commit 0108d7e

Browse files
solves reshape the matrix
1 parent 77c0df9 commit 0108d7e

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@
149149
| 559 | [Maximum Depth of N-Ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree) | Easy | [![Java](assets/java.png)](src/MaximumDepthOfNAryTree.java) [![Python](assets/python.png)](python/maximum_depth_of_n_ary_tree.py) |
150150
| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i) | Easy | [![Java](assets/java.png)](src/ArrayPartitionI.java) [![Python](assets/python.png)](python/array_partiton_I.py) |
151151
| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt) | Easy | [![Java](assets/java.png)](src/BinaryTreeTilt.java) [![Python](assets/python.png)](python/binary_tree_tilt.py) |
152-
| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | Easy | |
152+
| 566 | [Reshape The Matrix](https://leetcode.com/problems/reshape-the-matrix) | Easy | [![Java](assets/java.png)](src/ReshapeTheMatrix.java) [![Python](assets/python.png)](python/reshape_the_matrix.py) |
153153
| 572 | [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree) | Easy | |
154154
| 575 | [Distribute Candies](https://leetcode.com/problems/distribute-candies) | Easy | |
155155
| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray) | Easy | |

Diff for: python/reshape_the_matrix.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
6+
if r * c != len(mat) * len(mat[0]) or (r == len(mat) and c == len(mat[0])): return mat
7+
result = [[0] * c for _ in range(r)]
8+
k = 0
9+
for i in range(len(mat)):
10+
for j in range(len(mat[0])):
11+
result[k // c][k % c] = mat[i][j]
12+
k += 1
13+
return result

Diff for: src/ReshapeTheMatrix.java

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class ReshapeTheMatrix {
2+
public int[][] matrixReshape(int[][] mat, int r, int c) {
3+
if (r * c != mat.length * mat[0].length || (mat.length == r && mat[0].length == c)) return mat;
4+
5+
int[][] result = new int[r][c];
6+
for (int i = 0, k = 0 ; i < mat.length ; i++) {
7+
for (int j = 0 ; j < mat[0].length ; j++, k++) {
8+
result[k / c][k % c] = mat[i][j];
9+
}
10+
}
11+
return result;
12+
}
13+
}

0 commit comments

Comments
 (0)