螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix.length == 0)
return res;
// 定义四个指针,并且充当边界限制的作用
int top = 0, bottom = matrix.length-1;
int left = 0, right = matrix[0].length-1;
while( top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ){
//上面 左到右
for(int i = left; i <= right; i++){
res.add(matrix[top][i]);
}
//右边 上到下
for(int i = top+1; i <= bottom; i++){
res.add(matrix[i][right]);
}
//下面 右到左
for(int i = right-1; top!=bottom && i>=left; i--){
res.add(matrix[bottom][i]);
}
//左边 下到上
for(int i = bottom-1; left!=right && i>=top+1; i--){
res.add(matrix[i][left]);
}
// 遍历完一圈之后,所有往里面靠
++top;
--bottom;
++left;
--right;
}
return res;
}
}
矩阵置零
给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
示例:
输入:matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出:[[1,0,1],[0,0,0],[1,0,1]]
class Solution {
public void setZeroes(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0){
return;
}
int[] setI = new int[matrix.length];
int[] setJ = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == 0){
setI[i] = 1;
setJ[j] = 1;
}
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if(setI[i] == 1 || setJ[j] == 1){
matrix[i][j] = 0;
}
}
}
}
}