Leetcode—73.矩阵置零【中等】
2023-12-21 21:45:29
2023每日刷题(六十六)
Leetcode—73.矩阵置零
空间复杂度为O(m+n)版实现代码
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int rowLen = matrix.size();
int colLen = matrix[0].size();
vector<int> row(rowLen, 0);
vector<int> col(colLen, 0);
for(int i = 0; i < rowLen; i++) {
for(int j = 0; j < colLen; j++) {
if(matrix[i][j] == 0) {
row[i] = 1;
col[j] = 1;
}
}
}
for(int i = 0; i < rowLen; i++) {
for(int j = 0; j < colLen; j++) {
if(row[i] || col[j]) {
matrix[i][j] = 0;
}
}
}
}
};
运行结果
优化空间复杂度为O(1)版算法思想
优化版实现代码
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
bool rowFlag = false, colFlag = false;
int rowLen = matrix.size();
int colLen = matrix[0].size();
for(int i = 0; i < rowLen; i++) {
if(!matrix[i][0]) {
colFlag = true;
}
}
for(int j = 0; j < colLen; j++) {
if(!matrix[0][j]) {
rowFlag = true;
}
}
for(int i = 1; i < rowLen; i++) {
for(int j = 1; j < colLen; j++) {
if(!matrix[i][j]) {
matrix[i][0] = matrix[0][j] = 0;
}
}
}
for(int i = 1; i < rowLen; i++) {
for(int j = 1; j < colLen; j++) {
if(!matrix[i][0] || !matrix[0][j]) {
matrix[i][j] = 0;
}
}
}
if(colFlag) {
for(int i = 0; i < rowLen; i++) {
matrix[i][0] = 0;
}
}
if(rowFlag) {
for(int j = 0; j < colLen; j++) {
matrix[0][j] = 0;
}
}
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
文章来源:https://blog.csdn.net/qq_44631615/article/details/135139193
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!