-
Notifications
You must be signed in to change notification settings - Fork 5
/
ReshapeTheMatrix.java
58 lines (48 loc) · 2.12 KB
/
ReshapeTheMatrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Problem Statement:
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 column number 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.
Problem Link:
Reshape The Matrix: https://leetcode.com/problems/reshape-the-matrix/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/ReshapeTheMatrix.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
/*
A very simple solution: Traverse both new and old matrices together.
Keep two pointers - i, j - for new matrix's Row and column
Keep two pointers - iOriginal, jOriginal - for original matrix's Row and column
*/
public int[][] matrixReshape(int[][] nums, int r, int c) {
int rOriginal = nums.length;
int cOriginal = nums[0].length;
//If not possible to reshape, return original
if(rOriginal * cOriginal != r*c)
return nums;
int answer[][] = new int[r][];
int iOriginal =0,jOriginal=0;
for(int i =0;i<r ;i++){
answer[i]= new int[c];
for(int j =0;j<c ;j++){
//Copy the current element
answer[i][j]=nums[iOriginal][jOriginal];
//Slide the column pointer to right
jOriginal++;
//If already at the right end, slide to left and go to next row.
if(jOriginal >= cOriginal)
{
iOriginal++;
jOriginal=0;
}
}
}
return answer;
}
}