leetcode Set Matrix Zeroes
来源:互联网 发布:imovie mac 教程 编辑:程序博客网 时间:2024/06/06 07:07
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
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?
题中要求额外空间尽可能小,自己能想到最小额外空间也有m+n,用来记录哪一行、哪一列设为0
参考别人思路,可以不用多余的额外空间。具体思路就是使用原矩阵第0行,第0列来记录哪一行、哪一列设为0,代码思路如下:
class Solution {public: void setZeroes(vector<vector<int> >& matrix) { if(matrix.empty() || matrix.empty()) return; int row = matrix.size(); int sol = matrix[0].size(); int i, j; bool rowflag = false; bool solflag = false; //记录第0行、第0列中是否原来有0 for(j=0; j<sol; ++j) if(matrix[0][j]==0) solflag = true; for(i=0; i<row; ++i) if(matrix[i][0]==0) rowflag = true; //非第0行、第0列中元素为0,设置为该0元素对应的第0行、第0列为0,以用第0行、第0列来记录哪一列、哪一行中要设置为零 for(i=1; i<row; ++i) { for(j=1; j<sol; ++j) { if(matrix[i][j]==0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } //从1开始,因为要用第0行、第0列来记录哪一列、哪一行中要设置为零 for(i=1; i<row; ++i) if(matrix[i][0] == 0) for(j=1; j<sol; ++j) matrix[i][j] = 0; for(j=1; j<sol; ++j) if(matrix[0][j] == 0) for(i=1; i<row; ++i) matrix[i][j] = 0; //如果第0行、第0列中原来是否有0 if(solflag) for(j=0; j<sol;++j) matrix[0][j] = 0; if(rowflag) for(i=0; i<row; ++i) matrix[i][0] = 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
- API测试自动化
- rtp 解包h264
- Codeforces Round #368 (Div. 2) C Pythagorean Triples(构造勾股数)
- 3. Longest Substring Without Repeating Characters(难,重要)
- win7 caffe使用笔记——计算图像均值
- leetcode Set Matrix Zeroes
- Android之Http通信HttpConnection
- LA 3644并查集
- LruCache源码解析
- SPOJ COT(树上k大,主席树+LCA)
- FFmpeg音视频同步的问题
- 93.leetcode Restore IP Addresses(medium)[回溯 DFS]
- MySQL for mac 连接报错:Access denied for user 'root'@'localhost' (using password: YES)
- Codeforces Round #368 (Div. 2) D Persistent Bookcase(离线+DFS)