[LeetCode-Algorithms-73] "Set Matrix Zeroes" (2017.12.26-WEEK17)

来源:互联网 发布:sd卡损坏怎么恢复数据 编辑:程序博客网 时间:2024/05/21 10:53

题目链接: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.

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?


(1)思路:这道题最主要的是要求节省空间,降低空间复杂度到常数。那么就可以借助矩阵本身的空间,比如第一行和第一列来记录矩阵元素的0的情况。首先把第一行和第一列的元素检查一下,如果有0先记录下来但是不要对第一行和第一列处理。然后依次检查所有元素并处理,比如在第5行第6列找到了一个0,那么就把第一行第六列的元素变成0,同时把第五行第一列的元素变成0,检查完整个矩阵后根据第一行和第一列的0元素情况对矩阵进行整理,再把之前第一行和第一列的1情况还原回去。

(2)代码:

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

(3)提交结果:

这里写图片描述

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 中医养生培训 养生瑜伽 女子养生会所 养生吃什么好 女性养生保健大全 养生花茶 男性养生保健大全 养生中医馆 养生饮品 养生酒有哪些 女士养生会馆 冬季养生食谱 养生按摩 中医养生培训学校 十四经络养生 男性养生 养生有哪些项目 秋季滋补养生汤 高端养生 养生壶哪个品牌好 养生保健酒 保健养生馆 秋季女性养生 辟谷养生 养生保健品 养生足疗 按摩养生 九种体质养生 养生方法 养生术 美容院养生 养生太极拳 养生茶饮 养生足贴 高端养生会所 穴位养生 运动养生 保健养生酒 美容养生培训班 养生壶多少钱 健康养生常识