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.

    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,O(mn),即用的一个相同大小的矩阵来记录那个位置有0.

    2,O(m + n),就是加一行一列来标记哪行哪列有0。

    3,常数空间,即考虑不使用额外的空间,可以把第一行与第一列作为标记行与标记列,但是得先确定第一行与第一列本身要不要设为0。

    代码非常简单:

    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
           if (matrix.size() < 1) return;
             int row = matrix.size(), col = matrix[0].size();
             bool r0 = false, c0 = false;
             for (int i = 0; i < row; ++i) {
                 if (matrix[i][0] == 0) {
                     c0 = true; break;
                 }
             }
             for (int j = 0; j < col; ++j) {
                 if (matrix[0][j] == 0) {
                     r0 = true; break;
                 }
             }
             for (int i = 1; i < row; ++i) {
                 for (int j = 1; j < col; ++j) {
                     matrix[i][0] = (matrix[i][j] == 0) ? 0 : matrix[i][0];
                     matrix[0][j] = (matrix[i][j] == 0) ? 0 : matrix[0][j];
                 }   
             }
             for (int i = 1; i < row; ++i) {
                 for (int j = 1; j < col; ++j) {
                      matrix[i][j] = (matrix[i][0] == 0) ? 0 : matrix[i][j];
                      matrix[i][j] = (matrix[0][j] == 0) ? 0 : matrix[i][j];
                }   
             }
             for (int i = 0; i < row && c0; ++i)  matrix[i][0] = 0;
             for (int j = 0; j < col && r0; ++j)  matrix[0][j] = 0; 
        }
    };
  • 相关阅读:
    Nginx配置文件详解
    ngrinder 负载均衡脚本开发
    spring boot过滤器FilterRegistrationBean
    Spring boot 拦截器和过滤器
    spring controller中默认转发、forward转发、redirect转发之间的区别
    @RestControllerAdvice作用及原理
    Android APK脱壳--腾讯乐固、360加固一键脱壳
    java 简单xor加密
    facebook 研究
    阿里云docker安装
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4581259.html
Copyright © 2011-2022 走看看