zoukankan      html  css  js  c++  java
  • 19.2.13 [LeetCode 73] 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.

    Example 1:

    Input: 
    [
      [1,1,1],
      [1,0,1],
      [1,1,1]
    ]
    Output: 
    [
      [1,0,1],
      [0,0,0],
      [1,0,1]
    ]
    

    Example 2:

    Input: 
    [
      [0,1,2,0],
      [3,4,5,2],
      [1,3,1,5]
    ]
    Output: 
    [
      [0,0,0,0],
      [0,4,5,0],
      [0,3,1,0]
    ]
    

    Follow up:

    • 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

    题解

     1 class Solution {
     2 public:
     3     void setZeroes(vector<vector<int>>& matrix) {
     4         int m = matrix.size(), n = matrix[0].size();
     5         bool row = false, colum = false;
     6         for (int i = 0; i < m; i++)
     7             for (int j = 0; j < n; j++) {
     8                 if (matrix[i][j] == 0) {
     9                     if (i == 0)row = true;
    10                     if (j == 0)colum = true;
    11                     if(i!=0)
    12                         matrix[i][0] = 0;
    13                     if(j!=0)
    14                         matrix[0][j] = 0;
    15                 }
    16             }
    17         for (int i = 1; i < m; i++)
    18             for (int j = 1; j < n; j++)
    19                 if (!matrix[i][0] || !matrix[0][j])
    20                     matrix[i][j] = 0;
    21         if (colum) {
    22             for (int i = 0; i < m; i++)
    23                 matrix[i][0] = 0;
    24         }
    25         if(row){
    26             for (int j = 0; j < n; j++)
    27                 matrix[0][j] = 0;
    28         }
    29     }
    30 };
    View Code

    我一开始都没get到点在哪,试错之后才发现难点在哪……稍微用俩bool对 matrix[0][0] 的特殊情况处理一下就可以了

  • 相关阅读:
    lua的数组下标是从1开始的
    DestroyImmediate的一些坑
    c#的IDisposable
    unity工具开发(转)
    winform控件命名规范对照表
    C#调用Exe程序示例
    System.Diagnostics.Process.Start的妙用
    C#中AppDomain.CurrentDomain.BaseDirectory及各种路径获取方法
    C# WindowsAPI
    TabPage判断重复添加Page
  • 原文地址:https://www.cnblogs.com/yalphait/p/10371671.html
Copyright © 2011-2022 走看看