73. 矩陣置零
https://leetcode.cn/problems/set-matrix-zeroes/description/?envType=study-plan-v2&envId=top-100-liked
public void setZeroes(int[][] matrix) {
int top = 0,bottom = matrix.length,left = 0,right = matrix[0].length;
int[][] flag = new int[bottom][right];
for (int i = 0; i < bottom; i++) {
for (int j = 0; j < right; j++) {
if (matrix[i][j] == 0) flag[i][j] = 1;
}
}
for (int i = 0; i < bottom; i++) {
for (int j = 0; j < right; j++) {
if (flag[i][j] == 1){
for (int k = 0; k < i; k++) {
matrix[k][j] = 0;
}
for (int k = i; k < bottom; k++) {
matrix[k][j] = 0;
}
for (int k = 0; k < j; k++) {
matrix[i][k] = 0;
}
for (int k = j; k < right; k++) {
matrix[i][k] = 0;
}
}
}
}
}
總結:new一個陣列去記錄哪個位置是0 ,再把0的位置去上下左右變成0
54. 螺旋矩陣
https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
public List<Integer> spiralOrder(int[][] matrix) {
int top = 0 , bottom = matrix.length - 1 , left = 0 , right = matrix[0].length - 1;
int num = 0 ;
int tar = (bottom + 1) * (right + 1);
List<Integer> list = new ArrayList<>();
while (num < tar){
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
num++;
}
if (num == tar) break;;
top++;
for (int i = top; i <= bottom; i++) {
list.add(matrix[i][right]);
num++;
}
if (num == tar) break;;
right--;
for (int i = right; i >= left; i--) {
list.add(matrix[bottom][i]);
num++;
}
if (num == tar) break;;
bottom--;
for (int i = bottom; i >= top; i--) {
list.add(matrix[i][left]);
num++;
}
if (num == tar) break;;
left++;
}
return list;
}
總結:經典的矩陣問題,把top,left,bottom,right 這四個邊界弄明白就沒問題
48. 旋轉影像
https://leetcode.cn/problems/rotate-image/description/?envType=study-plan-v2&envId=top-100-liked
public void rotate(int[][] matrix) {
int top = 0,bottom = matrix.length - 1,left = 0,right = matrix[0].length - 1;
//f用來標記選擇的格子
int n = matrix.length;
for (int i = 0;i < n / 2;i++){
for (int f = left; f < right; f++) {
int iTop = matrix[top][f];
int iRight = matrix[f][right];
int iBottom = matrix[bottom][right - (f - left)];
int iLeft = matrix[bottom - (f - left)][left];
matrix[top][f] = iLeft;
matrix[f][right] = iTop;
matrix[bottom][right - (f - left)] = iRight;
matrix[bottom - (f - left)][left] = iBottom;
}
top++;
right--;
bottom--;
left++;
}
}
總結:一次轉四個,yeap
240. 搜尋二維矩陣 II
https://leetcode.cn/problems/search-a-2d-matrix-ii/?envType=study-plan-v2&envId=top-100-liked
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int r = 0;
int c = n - 1;
while (r < m && c >= 0){
if (matrix[r][c] == target) {
return true;
}else if (target > matrix[r][c]){
r++;
}else {
c--;
}
}
return false;
}
總結:此題可以看成右上角為root的二叉排序樹,很nice的思路,,無敵!