• 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.

    click to show follow up.

    Follow up:

    Did you use extra space?
    A straight forward solution using O(mn) space is probably a bad idea.
    A simple improvement uses O(m + n) space, but still not the best solution.
    Could you devise a constant space solution?

    分析:将数组中为0元素所在的行和列都置0。首先找到这些元素,分别开两个数组记录所在行和列,将这些行和列分别置0
    运行时间:87ms
     
     1 class Solution {
     2 public:
     3     void setZeroes(vector<vector<int>>& matrix) {
     4         int row = matrix.size();
     5         int col = matrix[0].size();
     6         
     7         vector<int> vRow(row, 0);
     8         vector<int> vCol(col, 0);
     9         for(int i = 0; i < row; i++){
    10             for(int j = 0; j < col; j++){
    11                 if(matrix[i][j] == 0){
    12                     vRow[i] = 1;
    13                     vCol[j] = 1;
    14                 }
    15             }
    16         }
    17         for(int i = 0; i < row; i++){
    18             if(vRow[i] == 1){
    19                 for(int j = 0; j < col; j++) matrix[i][j] = 0;
    20             }
    21         }
    22         for(int j = 0; j < col; j++){
    23             if(vCol[j] == 1){
    24                 for(int i = 0; i < row; i++) matrix[i][j] = 0;
    25             }
    26         }
    27         return;
    28     }
    29 };
  • 相关阅读:
    1059 C语言竞赛
    1058 选择题
    1057 数零壹
    1056 组合数的和
    1055 集体照
    Mysql--分库分表
    Mysql--改表结构
    Mysql--开始阶段
    Mysql--常用语句
    Mysql--grant授权
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4504672.html
Copyright © 2020-2023  润新知