zoukankan      html  css  js  c++  java
  • leetcode76set-matrix-zeroes

    题目描述

    给定一个m*n的矩阵,如果有一个元素是0,就把该元素所在的行和列上的元素全置为0,要求使用原地算法。
    拓展:
    你的算法有使用额外的空间吗?
    一种比较直接的算法是利用O(m,n)的空间,但是这不是一个好的解法
    使用简单的改进可以在O(m+n)的空间解决这个问题,但是还不是最佳的解法
    你能在常量级的空间复杂度内解决这个问题吗?

    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(m n) space is probably a bad idea.
    A simple improvement uses O(m + n) space, but still not the best solution.

    class Solution {
    public:
        void setZeroes(vector<vector<int> > &matrix) {
            const int row=matrix.size();
            const int col=matrix[0].size();
            bool row_flag=false,col_flag=false;
            
            for (int i=0;i<row ;i++)
                if (0==matrix [i][0])
                {
                    col_flag=true;
                    break;
                }
                
            
            for (int i=0;i<col;i++)
                if (0==matrix[0][i])
                {
                    row_flag=true;
                    break;
                }
            
            for (int i=1;i<row;i++)
                for (int j=1;j<col;j++)
                    if (0==matrix[i][j]){
                        
                    
                        matrix[i][0]=0;
                        matrix[0][j]=0;
                    }
                    
                
                
            
            for (int i=1;i<row;i++){
                for (int j=1;j<col;j++){
                    if (0==matrix[i][0] || matrix [0][j]==0)
                        matrix[i][j]=0;
                }
            }
            if (row_flag)
                for (int i=0;i<col;i++)
                    matrix[0][i]=0;
            if (col_flag)
                for (int i=0;i<row;i++)
                    matrix[i][0]=0;
            
        }
    };

  • 相关阅读:
    深入浅出WPF之Binding的使用(二)
    深入浅出WPF之Binding的使用(一)
    C#中XML的读取
    DependencyProperty属性介绍
    System.Windows.Markup.IQueryAmbient 在未被应用的程序集中定义
    Unity调用windows系统dialog 选择文件夹
    #if
    协程
    将[-1,1]映射到[0,1]
    Editor模式下实例化Prefab
  • 原文地址:https://www.cnblogs.com/hrnn/p/13403016.html
Copyright © 2011-2022 走看看