【程序员面试金典】面试题 01.08. 零矩阵
题目
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入: [ [1,1,1], [1,0,1], [1,1,1] ] 输出: [ [1,0,1], [0,0,0], [1,0,1] ]
示例 2:
输入: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] 输出: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
思路
使用临时数组进行标记。
代码
时间复杂度:O(mn)
空间复杂度:O(mn)
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { vector<vector<int>> tmp(matrix); for (int i = 0; i < tmp.size(); ++i) { for (int j = 0; j < tmp[0].size(); ++j) { if (tmp[i][j] == 0) { for (int k = 0; k < tmp[i].size(); ++k) matrix[i][k] = 0; for (int l = 0; l < tmp.size(); ++l) matrix[l][j] = 0; } } } } };
相关推荐
湾区人工智能 2020-11-20
diskingchuan 2020-10-23
amicablehj 2020-11-16
smartbaby 2020-11-11
teamvx 2020-11-11
啊兵 2020-11-10
ruancw 2020-11-10
Elyn 2020-11-08
susmote 2020-11-07
lipin 2020-11-03
kinglomei 2020-10-27
bucai 2020-10-26
JAVA飘香 2020-10-26
重剑无锋 2020-10-25
adentheima 2020-10-25
zhaoyinghuan 2020-10-25
Elyn 2020-10-24
lipin 2020-10-22
feinifi 2020-10-14