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

     由于题目要求用常量空间,故要利用matrix本身的空间

    本题将第1行和第1列作为重用空间

    首先寻找第1行和第1列是否含有0,如果含有0,标记下来,到最后再将第1行和第1列置为0

    现在遍历matrix其他元素,如果含有0,则将该行的第1个元素置为0, 将该列的第1个元素置为0,

    遍历完后,根据第一行和第1列将含有0的行和列置为0 即可

    class Solution {
    public:
        void setZeroes(vector<vector<int> > &matrix) {
            int n = matrix.size(), m = matrix[0].size();
            bool rowZero = false, colZero = false;
            for(int i = 0 ; i < m; ++ i) if(!matrix[0][i]) rowZero = true;
            for(int i = 0 ; i < n; ++ i) if(!matrix[i][0]) colZero = true;
            for(int i = 1 ; i < n; ++ i){
                for(int j = 1 ; j < m; ++ j){
                    if(!matrix[i][j]) {matrix[0][j]=0;matrix[i][0]=0;}
                }
            }
            for(int i =1; i < n ; ++ i){
                for(int j  =1; j < m; ++ j){
                    if(!matrix[0][j] || !matrix[i][0]) matrix[i][j] = 0;
                }
            }
            if(rowZero) for(int i = 0 ; i < m; ++ i) matrix[0][i] = 0;
            if(colZero) for(int i = 0 ; i < n; ++ i) matrix[i][0] = 0;
        }
    };
  • 相关阅读:
    apt update ,apt upgrade 和 apt dist-upgrade 的区别
    CVE-2018-8639 简单利用 win7
    如何拆解性能测试需求
    博客搬家啦
    驱动开发学习一
    驱动开发基础之数据结构
    c++容器加迭代器和python装饰器的对比
    c++简单学习
    windows下z3安装
    switch反汇编
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3811026.html
Copyright © 2011-2022 走看看