[leetcode]Set Matrix Zeroes

就是先遍历二维数组,然后用首行和首列作为标记是否整行整列要设为0。对于首行首列本身,另用两个boolean记录。

public class Solution {

    public void setZeroes(int[][] matrix) {

        // Start typing your Java solution below

        // DO NOT write main() function

        

        int m = matrix.length;

    	if (m == 0) return;

    	int n = matrix[0].length;

    	if (n == 0) return;

    	

    	boolean m0 = false;

    	boolean n0 = false;

    	for (int i = 0; i < m; i++) {

    		for (int j = 0; j < n; j++) {

    			if (matrix[i][j] == 0) {

    				matrix[i][0] = 0;

    				matrix[0][j] = 0;

    				if (i == 0) m0 = true;

    				if (j == 0) n0 = true;

    			}

    		}

    	}

    	

    	for (int i = 1; i < m; i++) {

    		for (int j = 1; j < n; j++) {

    			if (matrix[i][0] == 0 || matrix[0][j] == 0) {

    				matrix[i][j] = 0;

    			}

    		}

    	}

    	

    	if (m0) for (int i = 0; i < n; i++){

    		matrix[0][i] = 0;

    	}

    	if (n0) for (int i = 0; i < m; i++) {

    		matrix[i][0] = 0;

    	}

    }

}

参考答案中最后并不是遍历整个数组,而是遍历首行首列然后设0,但整体上复杂度不变。

你可能感兴趣的:(LeetCode)