Set Matrix Zeroes

来源:互联网 发布:淘宝店申请步骤 编辑:程序博客网 时间:2024/05/17 22:23

题目原型:

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

基本思路:

空间复杂度为O(mn)和O(m + n) 的思路比较容易想,关键是第三种,空间复杂度要求是o(1),其实这是第二种思路的变形,即把第一行和第一列拿出来存储需要置0的行列的记录。

//时间复杂度是O(1),借助了第一行和第一列,类似另外开辟空间来保存行和列的信息public void setZeroes(int[][] matrix){if(matrix==null||matrix.length==0)return;boolean isZeroFstRow = false;boolean isZeroFstCol = false;//寻找第一行是否有0for(int i = 0;i<matrix[0].length;i++){if(matrix[0][i]==0){isZeroFstRow = true;break;}}//寻找第一列是否有0for(int i = 0;i<matrix.length;i++){if(matrix[i][0]==0){isZeroFstCol = true;break;}}//记录需要置0的行列for(int i = 1;i<matrix.length;i++){for(int j = 1;j<matrix[0].length;j++){if(matrix[i][j]==0){matrix[i][0] = 0;matrix[0][j] = 0;}}}//置0for(int i = 1;i<matrix.length;i++){for(int j = 1;j<matrix[0].length;j++){if(matrix[i][0] == 0||matrix[0][j] == 0){matrix[i][j] = 0;}}}//如果第一行存在0,则把第一行置0if(isZeroFstRow){for(int i = 0;i<matrix[0].length;i++){matrix[0][i] = 0;}}//如果第一列存在0,则把第一列置0if(isZeroFstCol){for(int i = 0;i<matrix.length;i++){matrix[i][0] = 0;}}}



0 0
原创粉丝点击