LeetCode 之 Set Matrix Zeroes
来源:互联网 发布:vasp软件下载 编辑:程序博客网 时间:2024/06/03 19:59
原题:
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?
我用的就是O(m+n),即遍历数组,用row和col来保存要设为0的行和列,用的是unordered_set。。。有时间再优化。。。。。先睡了
代码如下(284ms):
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { unordered_set<int> row; unordered_set<int> col; for (int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[i].size();j++){ if(matrix[i][j] == 0){ if(row.find(i) == row.end()) row.insert(i); if(col.find(j) == col.end()) col.insert(j); } } } for ( auto it = row.begin(); it != row.end(); ++it ) { for(int i =0 ;i<matrix[*it].size();i++){ matrix[*it][i] = 0; } } for ( auto it = col.begin(); it != col.end(); ++it ) { for(int i =0 ;i<matrix.size();i++){ matrix[i][*it] = 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
- 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] Valid Parentheses
- Mapr升级方案(三)——脚本的滚动升级
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- Mapr升级步骤(四)——配置新版本
- [leet code]Maximum Depth of Binary Tree
- LeetCode 之 Set Matrix Zeroes
- Mapr升级步骤(五)——故障排除解决问题(一)
- 【Android应用开发详解】第01期:第三方授权认证(一)实现第三方授权登录、分享以及获取用户资料
- !!!Obj-c on Mac --- Chapter 15 File Loading and Saving
- Mapr搜索指南(一)——Mapr全文检索
- 投射在雾气中的可触摸未来屏
- x264_macroblock_cache_load()函数分析
- Java开发牛人十大必备网站
- 如何实现一个翻页效果的widget