题目描述

给定一个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;
        
    }
};

最新文章

  1. POJ 1743 Musical Theme 二分+后缀数组
  2. Linux 命令——grep | 正则表达式
  3. Android框架之AndroidAnnotations实战
  4. chrome浏览器不允许记忆登录账户的方法
  5. (7)基本工作流(使用AndroidStudio编辑Cocos项目)
  6. CentOS6.4 配置Nload监控网卡流量
  7. WinDump使用方法
  8. 单元测试之Fixture
  9. php设计模式--简单介绍
  10. 获取BDC 消息文本的2种方式
  11. 23.Hibernate-基础.md
  12. Javascript和JQuery函数定义方式
  13. 企业安全建设之搭建开源SIEM平台
  14. 笔记 freemark list标签迭代Map&lt;Map&lt;String,Object&gt;集合排序问题
  15. 关于jquery 取值,赋值常用控件的问题
  16. pandas生成时间列表(某段连续时间或者固定间隔时间段)
  17. MAVEN教程--01安装|创建|解释
  18. ssm项目快速搭建(注解)
  19. js随笔--关于数组
  20. 【LOJ】#2174. 「FJOI2016」神秘数

热门文章

  1. Mac安装mongodb并启动
  2. 基于python常用排序与查找
  3. 什么是 C 和 C ++ 标准库?学编程的你应该知道这些知识!
  4. Mysql数据库分布式事务XA详解
  5. docker查看ip
  6. PHP获取当前毫秒级别时间戳
  7. 使用原生js模拟jQuery选择器,实现new方法,兼容ie5
  8. 【服务总线 Azure Service Bus】ServiceBus 队列中死信(DLQ - Dead Letter Queue)问题
  9. python的部分GUI模块简介tkinter、pyqt5(Qt Designer)
  10. poj1655 Balancing Act (dp? dfs?)