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

LeetCode OJ 73. Set Matrix Zeroes

medium lac push_back 代碼 CP void solution 解答 vector

題目

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

解答

這題太水了,根本不是medium難度,一遍就AC了。

遍歷matrix,拿兩個數組分別記錄需要變成0的行和列就OK了。

下面是AC的代碼:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        vector<int> row, col;
        int
m = matrix.size(); if(m == 0){ return ; } int n = matrix[0].size(); for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(matrix[i][j] == 0){ row.push_back(i); col.push_back(j); } } } for
(vector<int>::iterator iter = row.begin(); iter != row.end(); iter++){ for(int i = 0; i < n; i++){ matrix[*iter][i] = 0; } } for(vector<int>::iterator iter = col.begin(); iter != col.end(); iter++){ for(int i = 0; i < m; i++){ matrix[i][*iter] = 0
; } } } };

113

LeetCode OJ 73. Set Matrix Zeroes