Set Matrix Zeroes
2015-08-25 22:18
330 查看
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?
Solution:
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?
Solution:
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(); if(!m) return ; int n = matrix[0].size(); if(!n) return ; int x = -1, y = -1; for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) { if(!matrix[i][j]) { if(x == -1 && y == -1) { x = i; y = j; } else { matrix[i][y] = 0; matrix[x][j] = 0; } } } if(x != -1 && y != -1) { for(int i = 0; i < n; ++i) { if(!matrix[x][i] && i != y) { for(int j = 0; j < m; ++j) matrix[j][i] = 0; } } for(int i = 0; i < m; ++i) { if(!matrix[i][y]) { for(int j = 0; j < n; ++j) matrix[i][j] = 0; } } for(int i = 0; i < m; ++i) matrix[i][y] = 0; } } };
相关文章推荐
- 数据库中索引的优缺点
- OC-属性
- 选举
- 安卓命令写入图片,微信相册中拿不到
- Android UI设计——ListView控件使用优化(五)
- 字符串全排列问题(递归回溯)
- Android Studio App设置Notification通知
- 8-25
- UVa 11536:Smallest Sub-Array(滑动窗口)
- VS2010 (C#)winform程序打包发布图解(转+自己修改)
- node.js(六) UTIL模块
- Flatten Binary Tree to Linked List
- linux下如何启动sybase
- 命令行参数
- OJ 刷题---串的简单处理
- 二十年目睹之怪状 序
- HDu 1198 Farm Irrigation
- 野人学Android基础篇之初探UI控件第三课--Button
- final、finally和finalize的区别
- final、finally和finalize的区别