Leetcode Set Matrix Zeroes
来源:互联网 发布:出货数据怎么做模板 编辑:程序博客网 时间:2024/05/16 13:54
Leetcode Set Matrix Zeroes 相关代码,应题目要求,本方法的空间复杂度为O(1),时间复杂度为O(m * n),cpp代码以及测试如下:
#include<iostream>#include<vector>using namespace std;// For the O(1) space constraint, we use the first row and the first column// record the zeros information.class Solution {public: void setZeroes(vector<vector<int> >& matrix) { if (matrix.size() == 0) { return; } int row = matrix.size(); int column = matrix[0].size(); int flag_row = 0; int flag_column = 0; // Record the first row zeros information. for (int j = 0; j < column; j ++) { if (matrix[0][j] == 0) { flag_row = 1; break; } } // Record the first column zeros information. for (int i = 0; i < row; i ++) { if (matrix[i][0] == 0) { flag_column = 1; break; } } // Find the zeros in [1..m, 1..n], and record the information in the // corespond first row and first column. for (int i = 1; i < row; i ++) { for (int j = 1; j < column; j ++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } // Using the recorded information to set the corespond row with zero. for (int i = 1; i < row; i ++) { if (matrix[i][0] == 0) { for (int j = 0; j < column; j ++) { matrix[i][j] = 0; } } } // Using the recorded information to set the corespond column with // zero. for (int j = 1; j < column; j ++) { if (matrix[0][j] == 0) { for (int i = 0; i < row; i ++) { matrix[i][j] = 0; } } } // Using the pre recorded information to set the first row. if (flag_row == 1) { for (int j = 0; j < column; j ++) { matrix[0][j] = 0; } } // Using the pre recorded information to set the first column. if (flag_column == 1) { for (int i = 0; i < row; i ++) { matrix[i][0] = 0; } } }};int main(int argc, char* argv[]) { Solution so; vector<vector<int> > test(4, vector<int>(4, 1)); test[0][0] = 0; test[2][2] = 0; so.setZeroes(test); for (int i = 0; i < test.size(); i ++) { for (int j = 0; j < test[0].size(); j ++) { cout<<test[i][j]<<" "; } cout<<endl; } cout<<endl; return 0;}
0 0
- LeetCode: Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- LeetCode-Set Matrix Zeroes
- [leetcode] Set Matrix Zeroes
- LeetCode - Set Matrix Zeroes
- Set Matrix Zeroes leetcode
- 【Leetcode】Set Matrix Zeroes
- 【leetcode】Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- Leetcode Set Matrix Zeroes
- LeetCode | Set Matrix Zeroes
- Word Pattern
- 数组名与指针的区别
- HDU2955 Robberies
- 学习笔记05-java异常
- LeakCanary 中文使用说明
- Leetcode Set Matrix Zeroes
- linux内核分析之system_call.s
- 申请博客的第一篇文章
- 编程思想之正则表达式
- 数据库事务四种隔离级别
- Oracle pl/sql编程 16---游标变量使用游标更新数据库
- linux常用命令
- Disruptor并发框架
- C++笔试面试遇到的问题