码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Set Matrix Zeroes

时间:2018-02-23 00:23:29      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:变量   dea   ide   dev   solution   tco   markdown   uri   pre   

Set Matrix Zeroes 题解

题目来源:https://leetcode.com/problems/set-matrix-zeroes/description/


Description

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?

Solution

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int row = matrix.size(), col = matrix[0].size();
        int i, j, col0 = 1;
        for (i = 0; i < row; i++) {
            if (matrix[i][0] == 0)
                col0 = 0;
            for (j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }

        for (i = row - 1; i >= 0; i--) {
            for (j = col - 1; j >= 1; j--) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
            if (col0 == 0)
                matrix[i][0] = 0;
        }
    }
};

解题描述

这道题题意是,给出一个矩阵,对其中为0,将其所在的列和行全部置为零。而附加的条件是,要求解法只有常数空间复杂度。上面给出的解法思想在于,在矩阵第一列保存所有行的状态,在矩阵第一行保存所有列的状态,而matrix[0][0]位置会出现重叠,所以要多用一个变量col0来保存第0列的状态。

[Leetcode] Set Matrix Zeroes

标签:变量   dea   ide   dev   solution   tco   markdown   uri   pre   

原文地址:https://www.cnblogs.com/yanhewu/p/8460560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!