LeetCode OJ 之 Set Matrix Zeroes (矩阵的置0)
来源:互联网 发布:卖家网wish数据 编辑:程序博客网 时间:2024/06/15 01:21
题目:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
给一个 m x n 矩阵,如果存在一个元素为0,则把此元素所在的行列元素都置为0.
Follow up:
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?
思路:
O(m + n)空间复杂度,可以设定两个bool型数组存储行和列上是否有0。
O(1)空间复杂度,可以利用二维数组的第一行和第一列。
代码1(空间复杂度为O(m + n) ):
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { if(matrix.empty()) return ; int row = matrix.size(); int col = matrix[0].size(); vector<bool> vecRow(row,false); vector<bool> vecCol(col,false); for(int i = 0 ; i < row ; i++) { for(int j = 0 ; j < col ; j++) { if(matrix[i][j] == 0) { vecRow[i] = true; vecCol[j] = true; } } } for(int i = 0 ; i < row ; i++) { if(vecRow[i]) for(int j = 0 ; j < col ; j++) { matrix[i][j] = 0; } } for(int i = 0 ; i < col ; i++) { if(vecCol[i]) for(int j = 0 ; j < row ; j++) { matrix[j][i] = 0; } } return; }};
代码2(空间复杂度为O(1)):
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { if(matrix.empty()) return ; int row = matrix.size(); int col = matrix[0].size(); bool rowHasZero = false; bool colHasZero = false; //判断第一列是否有0,如果有,则最后把第一列都置为0 for(int i = 0 ; i < row ; i++) { if(matrix[i][0] == 0) { colHasZero = true; break; } } //判断第一行是否有0,如果有,则最后把第一行都置为0 for(int i = 0 ; i < col ; i++) { if(matrix[0][i] == 0) { rowHasZero = 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(rowHasZero) { for(int i = 0 ; i < col ; i++) { matrix[0][i] = 0; } } if(colHasZero) { for(int i = 0 ; i < row ; i++) { matrix[i][0] = 0; } } return ; }};
0 0
- LeetCode OJ 之 Set Matrix Zeroes (矩阵的置0)
- 【LeetCode OJ】Set Matrix Zeroes
- LeetCode OJ:Set Matrix Zeroes
- LeetCode OJ Set Matrix Zeroes
- Set Matrix Zeroes 把一个矩阵置为0 @LeetCode
- LeetCode-73. Set Matrix Zeroes (JAVA) 矩阵元素置0
- LeetCode OJ 系列之73 Set Matrix Zeroes --Python
- 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 OJ算法题(七十三):Set Matrix Zeroes
- <LeetCode OJ> 73. Set Matrix Zeroes
- 【LeetCode OJ 073】Set Matrix Zeroes
- asp开发之mysql数据库的两种使用方法
- 2.3 键——超键、备选键、主键、引用完整性约束
- password密码输入框禁止copy cut paste,jQuery快速搞定
- Swift 实现UITableView报错, does not conform to protocol 'UITableViewDataSource'
- 火车头v8.5使用示例 采集手机号码
- LeetCode OJ 之 Set Matrix Zeroes (矩阵的置0)
- 利用sql server事件探查器排除与性能相关的问题
- Ubuntu-更新源
- python学习笔记(一)
- 查询Sql Server锁
- STM32 不同型号配置 MDK 工程
- 最大流算法 SAP+GAP
- SSH+JSP 图书管理系统
- C++简单的一个语句