zoukankan      html  css  js  c++  java
  • leetcode------Set Matrix Zeroes

    标题: Set Matrix Zeroes
    通过率: 31.3%
    难度: 中等

    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?

    本题的特点就是怎么用最少的额外空间去处理本题,最弱的也就是用另外一个mn的数组,或者就是用两个一维数组去记录行列,
    那么我想到的是不用任何额外的空间,方法如下:
    用数组的第0行和第0列去记录需要置0的行列,也就是说,如果matrix[i][j]=0那么需要把matrix[i][0]=0,matrix[0][j]=0的操作,这样一个
    m*n循环下来以后就把需要置0的行列进行的标记,!!!
    注意,在上一步之前先要确定第一行和第一列原来是否就有0的存在,这一部非常重要,如果不记录的话直接从上一步走,那么最好的结果是整个矩阵都是0,
    接着是置0操作,是从第一行第一列开始的!这一步也是非常关键,
    最后,要做的就是对第0行第0列进行操作,前面已经记录过是否有0,
    下面直接看代码:
     1 public class Solution {
     2     public void setZeroes(int[][] matrix) {
     3         int m=matrix.length;
     4         int n=matrix[0].length;
     5         boolean falg=false,mb=false,nb=false;
     6        
     7         for(int i=0;i<m;i++){
     8             if(matrix[i][0]==0){
     9                 mb=true;
    10             }
    11         }
    12         for(int i=0;i<n;i++){
    13             if(matrix[0][i]==0){
    14                 nb=true;
    15             }
    16         }
    17         for(int i=0;i<m;i++){
    18             for(int j=0;j<n;j++){
    19                 if(matrix[i][j]==0){
    20                     matrix[i][0]=0;
    21                     matrix[0][j]=0;
    22                 }
    23             }
    24         }
    25         for(int i=1;i<m;i++){
    26             for(int j=1;j<n;j++){
    27                 if(matrix[i][0]==0||matrix[0][j]==0){
    28                     matrix[i][j]=0;
    29                 }
    30             }
    31         }
    32         if(mb){
    33              for(int i=0;i<m;i++){
    34              matrix[i][0]=0;
    35             }
    36         }
    37         if(nb){
    38              for(int i=0;i<n;i++){
    39              matrix[0][i]=0;
    40             }
    41         }
    42     }
    43 
    44         
    45     
    46 }
  • 相关阅读:
    4.关于QT中的QFile文件操作,QBuffer,Label上加入QPixmap,QByteArray和QString之间的差别,QTextStream和QDataStream的差别,QT内存映射(
    PlSql加入数据库链接
    UserScan的处理流程分析
    第八十八题(金山笔试题,字符串移动)
    4Sum_leetCode
    LeetCode Add Binary
    Hibernate or JPA Annotation中BLOB、CLOB注解写法
    配置Nginx防止直接用IP訪问Webserver
    Java集合系列之TreeMap源代码分析
    使用Application Loader上传APP流程解读[APP公布]
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4281072.html
Copyright © 2011-2022 走看看