LeetCode_Study_Plan/Programming Skills
566. Reshape the Matrix java
개발하는루루
2022. 9. 21. 13:16
https://leetcode.com/problems/reshape-the-matrix/?envType=study-plan&id=programming-skills-i
Reshape the Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
public int[][] matrixReshape(int[][] mat, int r, int c) {
int[][] ans = new int[r][c];
if ((r == mat.length && c == mat[0].length) || r * c != mat.length * mat[0].length) return mat;
int x = 0, y = 0; // x, y는 새로운 matrix용
for (int i = 0; i < mat.length; i++){ //i, j는 원본 matrix용
for (int j = 0; j < mat[0].length; j++){
if (y == c) {
x++; //column이 넘쳐버리면 x를 한칸 더 늘려야 함
y = 0;
}
System.out.println("x:" + x + " y:" + y + " i:" + i + " j:" + j);
ans[x][y] = mat[i][j];
y++;
}
System.out.println(Arrays.deepToString(ans));
}
return ans;
}
두 개의 메트릭스 i, j / x, y 를 구별하는 것에서 에러처리가 한번 있었고,
test case 4번 예제를 보면
위와 같이 reshape이 불가능한 구조를 상상해봤을 때 반복문을 돌기 전에 에러처리를 할 수 있었다.
조금 더 응용해본다면 처음부터 사이즈를 같다면 원래의 matrix를 그대로 뱉음으로 시간을 절약할 수 있다.