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

    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?

    提示:

    这题要求用常数的空间去解决,那么我们就可以利用第一行和第一列的元素去标记该行或该列是否在更新时要全部变成0。但是单纯这样操作会使得第一行和第一列的原始状态丢失。

    因此,我们需要额外一个变量去保存第一列(或者第一行也可以)在更新时是否要变成0,这样就不会有问题了。

    另外还有一个让代码更加精简的小窍门,就是在更新的时候从下往上(Bottom-Up),这样就不用担心会破坏第一行或第一列的数据了。

    代码:

    class Solution {
    public:
        void setZeroes(vector<vector<int>>& matrix) {
            int height = matrix.size();
            int width = height ? matrix[0].size() : 0;
            if (!height || !width) {
                return;
            }
            int col0 = 1;
            for (int i = 0; i < height; ++i) {
                if (matrix[i][0] == 0) {
                    col0 = 0;
                }
                for (int j = 1; j < width; ++j) {
                    if (matrix[i][j] == 0) {
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }
                }
            }
            for (int i = height - 1; i >= 0; --i) {
                for (int j = width - 1; j >= 1; --j) {
                    if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                        matrix[i][j] = 0;
                    }
                }
                if (col0 == 0) {
                    matrix[i][0] = 0;
                }
            }
        }
    };
  • 相关阅读:
    值得收藏的14款响应式前端开发框架
    简单几步把LOGO变字体
    7 款免费的 Metro UI 模板
    JPG渐进 & PNG/PNG24 交错测试
    你的钱,以后是放银行还是放支付宝?
    Bise IE6 在你的网站上加上它让IE滚蛋吧
    单例模式常见场景
    10 个最新的开发者工具
    大流量网站的底层系统架构
    DNS解析全过程及原理
  • 原文地址:https://www.cnblogs.com/jdneo/p/5238643.html
Copyright © 2011-2022 走看看