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

    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?

    思路

    直接的思路是用o(m+n)的空间来记录m行和n列是否存在0, 但是需要用固定空间的解决方法,可以考虑使用原先数据提供的空间,进而想到用原数组的第一行和第一列来记录。另外由于还需要第一行和第一列是否需要置为0,所以使用两个bool变量来存储原先第一行和第一列是否存在0即可。

    代码

     1     void setZeroes(vector<vector<int> > &matrix) {
     2         // Note: The Solution object is instantiated only once and is reused by each test case.
     3         bool hasZeroRow = false, hasZeroColumn = false;
     4         int i,j;
     5         int m = matrix.size();
     6         if(m == 0)
     7             return;
     8         int n = matrix[0].size();
     9         if(n == 0)
    10             return;
    11         for(i = 0; i < n; i++){
    12             if(matrix[0][i] == 0){
    13                 hasZeroRow = true;
    14                 break;
    15             }
    16         }
    17         for(i = 0; i < m; i++){
    18             if(matrix[i][0] == 0){
    19                 hasZeroColumn = true;
    20                 break;
    21             }
    22         }
    23         for(i = 1; i < m; i++){
    24             for(j = 1; j < n; j++){
    25                 if(matrix[i][j] == 0){
    26                     matrix[0][j] = 0;
    27                     matrix[i][0] = 0;
    28                 }
    29             }
    30         }
    31         for(i = 1; i < n; i++){
    32             if(matrix[0][i] == 0){
    33                 for(j = 0; j < m; j++){
    34                     matrix[j][i] = 0;
    35                 }
    36             }
    37         }
    38         for(i = 1; i < m; i++){
    39             if(matrix[i][0] == 0){
    40                 for(j = 0; j < n; j++){
    41                     matrix[i][j] = 0;
    42                 }
    43             }
    44         }
    45         if(hasZeroRow){
    46             for(i = 0; i < n; i++)
    47                 matrix[0][i] = 0;
    48         }
    49         if(hasZeroColumn){
    50             for(i = 0; i < m; i++)
    51                 matrix[i][0] = 0;
    52         }
    53     }
  • 相关阅读:
    Ado.Net Entity Framework 批量删除、判断存在
    Asp.Net MVC 3 与 HTML 5
    Entity SQL 时间条件比较
    Visual Studio 2010 调试 C 语言程序
    XAML 属性设置Windows Phone笔记
    SQL Server 2008 R2 数据库之间的数据同步热备份
    SQL Server 2008 R2 SP1正式版发布
    一个 Windows Form Demo
    PL SQL 9 安装 并连接 64位 Oracle 11G
    转载:如何稳定地使用 Google 搜索
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3388423.html
Copyright © 2020-2023  润新知