Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit a5d0180

Browse files
committed
Add problem 566
1 parent aeb6522 commit a5d0180

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

‎algorithms/566/README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
## 566. Reshape the Matrix
2+
3+
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.
4+
5+
You're given a matrix represented by a two-dimensional array, and two **positive** integers **r** and **c** representing the **row** number and **column** number of the wanted reshaped matrix, respectively.
6+
7+
The reshaped matrix need to be filled with all the elements of the original matrix in the same **row-traversing** order as they were.
8+
9+
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
10+
11+
**Example 1:**
12+
<pre>
13+
<b>Input:</b>
14+
nums =
15+
[[1,2],
16+
[3,4]]
17+
r = 1, c = 4
18+
<b>Output:</b>
19+
[[1,2,3,4]]
20+
<b>Explanation:</b>
21+
The <b>row-traversing</b> of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill
22+
it row by row by using the previous list.
23+
</pre>
24+
25+
**Example 2:**
26+
<pre>
27+
<b>Input:</b>
28+
nums =
29+
[[1,2],
30+
[3,4]]
31+
r = 2, c = 4
32+
<b>Output:</b>
33+
[[1,2],
34+
[3,4]]
35+
<b>Explanation:</b>
36+
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original
37+
matrix.
38+
</pre>
39+
40+
**Note:**
41+
42+
1. The height and width of the given matrix is in range [1, 100].
43+
2. The given r and c are all positive.

‎algorithms/566/solution.go‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package main
2+
3+
// Time and space complexity, O(r*c)
4+
func matrixReshape(nums [][]int, r int, c int) [][]int {
5+
if len(nums)*len(nums[0]) != r*c {
6+
return nums
7+
}
8+
9+
matrix := make([][]int, r)
10+
matrix[0] = make([]int, c)
11+
rr, cc := len(nums), len(nums[0])
12+
for i, j, ii := 0, 0, 0; ii < rr; ii++ {
13+
for jj := 0; jj < cc; jj++ {
14+
if j == c {
15+
i++
16+
matrix[i] = make([]int, c)
17+
j = 0
18+
}
19+
matrix[i][j] = nums[ii][jj]
20+
j++
21+
}
22+
}
23+
return matrix
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /