zoukankan      html  css  js  c++  java
  • Set Matrix Zeroes leetcode

    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.

     

    Subscribe to see which companies asked this question

    方法:用矩阵中的某一零行来记录零列的信息

    过程如下:

    1.从下往上遍历矩阵,找到第一个0元素,我们将其所在行作为记录行,用它来记录列号

    2.接着从上向下遍历矩阵,找到0元素,将其所在行赋值为0,并在记录行中同列的元素赋值为0,作为记录

    3.根据记录行中的记录,将0元素所在的列全部赋值为0

    4.将记录行赋值为0

    void setZeroes(vector<vector<int>>& matrix) {
        const int h = matrix.size();
        const int w = matrix[0].size();
        int store = -1;
        for (int i = h - 1; i >= 0; --i)
        {
            if (store != -1)
                break;
            for (int j = 0; j < w; ++j)
            {
                if (matrix[i][j] == 0)
                {
                    store = i;
                    break;
                }
            }
        }
        if (store == -1)
            return;
        for (int i = 0; i < store; ++i)
        {
            bool isZero = false;
            for (int j = 0; j < w; ++j)
            {
                if (matrix[i][j] == 0)
                {
                    matrix[store][j] = 0;
                    isZero = true;
                }
            }
            if (isZero)
                for (int j = 0; j < w; ++j)
                    matrix[i][j] = 0;
        }
    
        for (int j = 0; j < w; ++j)
            if(matrix[store][j] == 0)
                for (int i = 0; i < h; ++i)
                    matrix[i][j] = 0;
    
        for (int j = 0; j < w; ++j)
            matrix[store][j] = 0;
    }
  • 相关阅读:
    Eclipse JSP/Servlet 环境搭建
    2017 世界主要国家和地区 GDP 排名
    Twsited异步网络框架
    RabbitMQ队列,RedisMemcached缓存
    Paramiko,数据库
    SelectPollEpoll异步IO与事件驱动
    进程,线程,协程
    socketserver模块
    socket
    类的相关知识
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5134581.html
Copyright © 2011-2022 走看看