zoukankan      html  css  js  c++  java
  • 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?

     
     1 public class Solution {
     2     public void setZeroes(int[][] matrix) {
     3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
     4         int row = 0, col = 0;
     5         boolean sig = true;
     6         for(int i = 0; i < matrix.length; i ++){
     7             for(int j = 0; j < matrix[0].length; j ++){
     8                 if(matrix[i][j] == 0){
     9                     if(sig){
    10                         row = i;
    11                         col = j;
    12                         sig = false;
    13                     } else {
    14                         matrix[row][j] = 0;
    15                         matrix[i][col] = 0;
    16                     }
    17                 }
    18             }
    19         }
    20         if(sig) return;
    21         for(int i = 0; i < matrix.length; i ++){
    22             for(int j = 0; j < matrix[0].length; j ++){
    23                 if((matrix[row][j] == 0 || matrix[i][col] == 0) && i != row && j != col) matrix[i][j] = 0;
    24             }
    25         }
    26         for(int i = 0; i < matrix.length; i ++){
    27             matrix[i][col] = 0;
    28         }
    29         for(int j = 0; j < matrix[0].length; j ++){
    30             matrix[row][j] = 0;
    31         }
    32     }
    33 }
  • 相关阅读:
    0918作业-----所有数值未做合法性检测
    尝试安装和配置JDK,并给出安装、配置JDK的步骤
    java为什么可以跨平台执行
    字符集
    java 入门及简介
    时间轴特效
    javascript简介
    javascript while循环
    Javascript for循环
    函数豹子问题
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3957170.html
Copyright © 2011-2022 走看看