2.1.19 Set Matrix Zeroes
来源:互联网 发布:购买域名需要多少钱 编辑:程序博客网 时间:2024/06/11 04:46
Notes:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
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?
Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.
class Solution {public: void setZeroes(vector<vector<int>> &matrix) { if (matrix.empty()) return; int N = matrix.size(), M = matrix[0].size(); bool setFirstRowZero = false; bool setFirstColZero = false; for (int i = 0; i < N && !setFirstColZero; ++i) setFirstColZero = (matrix[i][0] == 0); for (int j = 0; j < M && !setFirstRowZero; ++j) setFirstRowZero = (matrix[0][j] == 0); 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; } 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; if (setFirstRowZero) for (int j = 0; j < M; ++j) matrix[0][j] = 0; if (setFirstColZero) for (int i = 0; i < N; ++i) matrix[i][0] = 0; }};
0 0
- 2.1.19 Set Matrix Zeroes
- 2.1.20 Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- war包通过ant远程发布到weblogic
- 文件简易批量编号
- iOS7 edgesForExtendedLayout
- 解决float元素父元素高度为0的代码&根据浏览器版本引用js代码,代码备用
- 敌兵布阵
- 2.1.19 Set Matrix Zeroes
- RS232接口简介
- TNS-01155: Incorrectly specified SID_LIST_LISTENER parameter in LISTENER.ORA NL-00303: syntax error
- DesignPatterns_Command
- XCode中创建第一个类
- 二进制 位与(或)使用
- 在Java中计算四则运算表达式字符串的值
- 新浪微博—随便看看
- 了解到的一些接口及方法