-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmatrixReshape.java
52 lines (38 loc) · 1.26 KB
/
matrixReshape.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
// Using Queue - Extra space
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length, n = nums[0].length;
if(m * n != r * c) return nums;
Queue<Integer> queue = new LinkedList<>();
for(int i=0; i<nums.length; i++)
for(int j=0; j<nums[0].length; j++)
queue.offer(nums[i][j]);
int [][] result = new int[r][c];
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
result[i][j] = queue.poll();
return result;
}
}
// Without using extra space
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length, n = nums[0].length, row = 0, col = 0;
if(m * n != r * c) return nums;
int [][] result = new int[r][c];
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
result[row][col] = nums[i][j];
col++;
if(col == c)
{
col = 0;
row++;
}
}
}
return result;
}
}