博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Set Matrix Zeroes
阅读量:4150 次
发布时间:2019-05-25

本文共 2390 字,大约阅读时间需要 7 分钟。

class Solution {//let the first row and first col to keep the record//if matrix[row][col] == 0 && col == 0, then firstColZero = true, same to firstRowZeropublic:	void setZeroes(vector
> &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int rowNum = matrix.size(); if(0 == rowNum) return; int colNum = matrix[0].size(); bool firstRowZero, firstColumnZero; firstRowZero = firstColumnZero = false; for (int row = 0; row < rowNum; ++row) { for (int col = 0; col < colNum; ++col) { if (!matrix[row][col]) { if(row == 0) firstRowZero = true; if(col == 0) firstColumnZero = true; matrix[row][0] = 0; matrix[0][col] = 0; } } } //according the flag in first row and first col to set the row and col to zero corresponding for(int row = 1; row < rowNum; ++row) { if(0 == matrix[row][0]) { for (int col = 0; col < colNum; ++col) matrix[row][col] = 0; } } // for(int col = 1; col < colNum; ++col) { if(0 == matrix[0][col]) { for (int row = 0; row < rowNum; ++row) matrix[row][col] = 0; } } // if(firstRowZero) for (int col = 0; col < colNum; ++col) matrix[0][col] = 0; if(firstColumnZero) for (int row = 0; row < rowNum; ++row) matrix[row][0] = 0; }};

second time

class Solution {public:    void setZeroes(vector
> &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = matrix.size(); if(n == 0) return; int m = matrix[0].size(); if(m == 0) return; bool firstRow = false; bool firstColumn = false; for(int i = 0; i < n; ++i) { if(matrix[i][0] == 0) { firstColumn = true; break; } } for(int j = 0; j < m; ++j) { if(matrix[0][j] == 0) { firstRow = true; break; } } //using first row and first column to keep record for(int i = 1; i < n; ++i) { for(int j = 1; j < m; ++j) { if(matrix[i][j] == 0) matrix[0][j] = 0, matrix[i][0] = 0; } } //set zero for(int i = 1; i < n; ++i) { if(matrix[i][0] == 0) { for(int j = 1; j < m; ++j) matrix[i][j] = 0; } } for(int j = 1; j < m; ++j) { if(matrix[0][j] == 0) { for(int i = 1; i < n; ++i) matrix[i][j] = 0; } } //set first row and first colum if(firstRow) { for(int j = 0; j < m; ++j) matrix[0][j] = 0; } if(firstColumn) { for(int i = 0; i < n; ++i) matrix[i][0] = 0; } }};

转载地址:http://tqxti.baihongyu.com/

你可能感兴趣的文章
实验3-5 编程初步
查看>>
实验4-1 逻辑量的编码和关系操作符
查看>>
实验5-2 for循环结构
查看>>
实验5-3 break语句和continue语句
查看>>
实验5-4 循环的嵌套
查看>>
实验5-5 循环的合并
查看>>
实验5-6 do-while循环结构
查看>>
实验5-7 程序调试入门
查看>>
实验5-8 综合练习
查看>>
第2章实验补充C语言中如何计算补码
查看>>
深入入门正则表达式(java) - 命名捕获
查看>>
使用bash解析xml
查看>>
android系统提供的常用命令行工具
查看>>
【Python基础1】变量和字符串定义
查看>>
【Python基础2】python字符串方法及格式设置
查看>>
【Python】random生成随机数
查看>>
【Python基础3】数字类型与常用运算
查看>>
Jenkins迁移jobs
查看>>
【Python基础4】for循环、while循环与if分支
查看>>
【Python基础5】列表和元组
查看>>