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的思路,,无敌!
标签:right,matrix,48,bottom,int,LeetCodeHot100,矩阵,++,left From: https://www.cnblogs.com/jeasonGo/p/18073713