Algorithms—73.Set Matrix Zeroes

原创 2015年07月09日 21:38:32

思路:首先是O(m+n)空间复杂度的方法,新开辟空间,然后遍历所有的点,如果有那个点的值为0,则将其横纵坐标的值记录进去。然后是空间复杂度为常数的。即把这些横纵坐标记录在原数组中,改为0即可。但是需要注意的是2点,1.在查询前先判断(x,0)和(0,y)两条线上是否存在0的点。2.重新遍历赋值的时候值修改除上述2条线的内部结构。3.再根据1中查询的结果决定是否修改这2条线。

public class Solution {
    public void setZeroes(int[][] matrix) {
    	boolean f=true;
    	for (int i = 0; i < matrix.length; i++) {
			if (matrix[i][0]==0) {
				f=false;
				break;
			}
		}
    	boolean l=true;
    	for (int i = 0; i < matrix[0].length; i++) {
			if (matrix[0][i]==0) {
				l=false;
			}
		}
        for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				if (matrix[i][j]==0) {
					matrix[i][0]=0;
					matrix[0][j]=0;
				}
			}
		}
        for (int i = 1; i < matrix.length; i++) {
			for (int j = 1; j < matrix[i].length; j++) {
				if (matrix[i][0]==0||matrix[0][j]==0) {
					matrix[i][j]=0;
				}
			}
		}
        if (!f) {
			for (int i = 0; i < matrix.length; i++) {
				matrix[i][0]=0;
			}
		}
        if (!l) {
        	for (int i = 0; i < matrix[0].length; i++) {
				matrix[0][i]=0;
			}
		}
    }
}


耗时:396ms,中游。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode 73. Set Matrix Zeroes (Medium) (cpp)

Leetcode 73. Set Matrix Zeroes (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年07月27日 21:21
  • 636

【LeetCode】73. Set Matrix Zeroes解法及注释

73. Set Matrix Zeroes Given a m x n matrix, if an element is 0, set its entire row and column to ...

[LeetCode]73.Set Matrix Zeroes

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

LeetCode(73)Set Matrix Zeroes

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

Leetcode NO.73 Set Matrix Zeroes

本题要求如下: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in ...

(java)leetcode-73:Set Matrix Zeroes

Set Matrix Zeroes Given a m x n matrix, if an element is 0, set its entire row and column to 0. D...

Leetcode OJ 73 Set Matrix Zeroes [Medium]

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

leetcode_question_73 Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Foll...
  • doc_sgl
  • doc_sgl
  • 2013年09月19日 21:47
  • 4202

LeetCode 73 Set Matrix Zeroes(Python详解及实现)

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

[leetcode] 【数组】73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. 题意 ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Algorithms—73.Set Matrix Zeroes
举报原因:
原因补充:

(最多只允许输入30个字)