[leetcode]73. Set Matrix Zeroes(Java)

来源:互联网 发布:福州火车站地下淘宝城 编辑:程序博客网 时间:2024/06/11 03:36

https://leetcode.com/problems/set-matrix-zeroes/#/description


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.


package go.jacob.day628;import java.util.HashSet;public class Demo3 {/* * Runtime: 2 ms.Your runtime beats 27.13 % of java submissions. */public void setZeroes(int[][] matrix) {//fr和fc用来记录第一行和第一列是否要置0boolean fr = false, fc = false;for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[0].length; j++) {//如果[i,j]为0,把该元素所在的行列头元素设为0if (matrix[i][j] == 0) {if (i == 0)fr = true;if (j == 0)fc = true;matrix[0][j] = 0;matrix[i][0] = 0;}}}for (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;}}}//判断,将首行首列置为零if (fr) {for (int j = 0; j < matrix[0].length; j++) {matrix[0][j] = 0;}}if (fc) {for (int i = 0; i < matrix.length; i++) {matrix[i][0] = 0;}}}/* * Solution by me. */public void setZeroes_1(int[][] matrix) {if (matrix == null || matrix.length == 0 || matrix[0].length == 0)return;int m = matrix.length;int n = matrix[0].length;HashSet<Integer> rows = new HashSet<Integer>();HashSet<Integer> cols = new HashSet<Integer>();for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (rows.contains(i) && cols.contains(j))continue;if (matrix[i][j] == 0) {rows.add(i);cols.add(j);}}}for (int i : rows) {for (int j = 0; j < n; j++) {matrix[i][j] = 0;}}for (int i : cols) {for (int j = 0; j < m; j++) {matrix[j][i] = 0;}}}}


原创粉丝点击