public class DayCode {
public static void main(String[] args) {
int[][] nums = new int[][]{{1, 2}, {3, 4}};
int r = 1;
int c = 4;
int[][] ans = new DayCode().matrixReshape(nums, r, c);
System.out.println("ans is " + Arrays.deepToString(ans));
}
/**
* https://leetcode-cn.com/problems/reshape-the-matrix/
* @param nums
* @param r
* @param c
* @return
*/
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length;
int n = nums[0].length;
if (m * n != r * c) {
return nums;
}
int[][] ans = new int[r][c];
int newX = 0;
int newY = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
ans[newX][newY] = nums[i][j];
newY++;
if (newY >= c) {
newX++;
newY = 0;
}
}
}
return ans;
}
/**
* https://leetcode-cn.com/problems/reshape-the-matrix/
* @param nums
* @param r
* @param c
* @return
*/
public int[][] matrixReshape2(int[][] nums, int r, int c) {
int m = nums.length;
int n = nums[0].length;
if (m * n != r * c) {
return nums;
}
int[][] ans = new int[r][c];
for (int x = 0; x < m * n; x++) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
}
评论