0
点赞
收藏
分享

微信扫一扫

LeetCode73. 矩阵置零


给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用​​原地​​算法

示例 1:


输入: [   [1,1,1],   [1,0,1],   [1,1,1] ] 输出: [   [1,0,1],   [0,0,0],   [1,0,1] ]


示例 2:


输入: [   [0,1,2,0],   [3,4,5,2],   [1,3,1,5] ] 输出: [   [0,0,0,0],   [0,4,5,0],   [0,3,1,0] ]


进阶:

  • 一个直接的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
  • 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
  • 你能想出一个常数空间的解决方案吗?

思路:先找出数组元素等于0的索引i,j;再根据索引将数组重新赋值。

class Solution {
public void setZeroes(int[][] matrix) {
List<List<Integer>> list=new LinkedList<List<Integer>>();//用来存储数组中元素值==0的索引

for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if(matrix[i][j]==0){
List<Integer> tmp=new LinkedList<Integer>();
tmp.add(i);
tmp.add(j);
list.add(tmp);
}
}
}

//将索引处的行列元素都赋0
for(List<Integer> l:list){
for(int i=0;i<matrix.length;i++){
matrix[i][l.get(1)]=0;
}
for(int j=0;j<matrix[0].length;j++){
matrix[l.get(0)][j]=0;
}
}
}
}

 

举报

相关推荐

0 条评论