1. 程式人生 > >73. Set Matrix Zeroes

73. Set Matrix Zeroes

tps clas problem discuss log 部分 bool .com size

題目:

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

鏈接: http://leetcode.com/problems/set-matrix-zeroes/

5/28/2017

3ms, 17%

先確定第一行和第一列是否應該全部置為0,用firstRow, firstColumn表示。這裏不改數組的原因是這一行一列會被用作其他行列的標誌位。

遍歷其他行列,並將第一行第一列相應元素設為0

遍歷第一行第一列將相應元素設為0

 1 public class Solution {
 2
public void setZeroes(int[][] matrix) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 4 return; 5 } 6 int row = matrix.length; 7 int column = matrix[0].length; 8 boolean firstRow = false, firstColumn = false; 9 10
if (!firstColumn) { 11 for (int i = 0; i < row; i++) { 12 if (matrix[i][0] == 0) { 13 firstColumn = true; 14 break; 15 } 16 } 17 } 18 if (!firstRow) { 19 for (int i = 0; i < column; i++) {
20 if (matrix[0][i] == 0) { 21 firstRow = true; 22 break; 23 } 24 } 25 } 26 for (int i = 1; i < row; i++) { 27 for (int j = 1; j < column; j++) { 28 if (matrix[i][j] == 0) { 29 matrix[0][j] = 0; 30 matrix[i][0] = 0; 31 } 32 } 33 } 34 for (int i = 1; i < row; i++) { 35 if (matrix[i][0] == 0) { 36 for (int j = 1; j < column; j++) { 37 matrix[i][j] = 0; 38 } 39 } 40 } 41 for (int i = 1; i < column; i++) { 42 if (matrix[0][i] == 0) { 43 for (int j = 1; j < row; j++) { 44 matrix[j][i] = 0; 45 } 46 } 47 } 48 if (firstColumn) { 49 for (int i = 0; i < row; i++) { 50 matrix[i][0] = 0; 51 } 52 } 53 if (firstRow) { 54 for (int i = 0; i < column; i++) { 55 matrix[0][i] = 0; 56 } 57 } 58 return; 59 } 60 }

別人的算法,大部分跟我寫的一樣。有一個特別精簡的:設第一行第一列用top-down,設其他元素用bottom-up

https://discuss.leetcode.com/topic/5056/any-shorter-o-1-space-solution

 1 void setZeroes(vector<vector<int> > &matrix) {
 2     int col0 = 1, rows = matrix.size(), cols = matrix[0].size();
 3 
 4     for (int i = 0; i < rows; i++) {
 5         if (matrix[i][0] == 0) col0 = 0;
 6         for (int j = 1; j < cols; j++)
 7             if (matrix[i][j] == 0)
 8                 matrix[i][0] = matrix[0][j] = 0;
 9     }
10 
11     for (int i = rows - 1; i >= 0; i--) {
12         for (int j = cols - 1; j >= 1; j--)
13             if (matrix[i][0] == 0 || matrix[0][j] == 0)
14                 matrix[i][j] = 0;
15         if (col0 == 0) matrix[i][0] = 0;
16     }
17 }

更多討論

https://discuss.leetcode.com/category/81/set-matrix-zeroes

73. Set Matrix Zeroes