set-matrix-zeroes
来源:互联网 发布:qq三国70js橙鬼 编辑:程序博客网 时间:2024/06/07 01:43
题目:
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(m n) 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?
程序:
class Solution {public: void setZeroes(vector<vector<int> > &matrix) { const int row = matrix.size(); const int col = matrix[0].size(); bool row_flg = false, col_flg = false; //判断第一行和第一列是否有零,防止被覆盖 for (int i = 0; i < row; i++) if (0 == matrix[i][0]) { col_flg = true; break; } for (int i = 0; i < col; i++) if (0 == matrix[0][i]) { row_flg = true; break; } //遍历矩阵,用第一行和第一列记录0的位置 for (int i = 1; i < row; i++) for (int j = 1; j < col; j++) if (0 == matrix[i][j]) { matrix[i][0] = 0; matrix[0][j] = 0; } //根据记录清零 for (int i = 1; i < row; i++) for (int j = 1; j < col; j++) if (0 == matrix[i][0] || 0 == matrix[0][j]) matrix[i][j] = 0; //最后处理第一行 if (row_flg) for (int i = 0; i < col; i++) matrix[0][i] = 0; if (col_flg) for (int i = 0; i < row; i++) matrix[i][0] = 0; }};
阅读全文
0 0
- 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
- Leetcode:Set Matrix Zeroes
- Set Matrix Zeroes
- 第二周项目2-程序的多文件组织
- elasticsearch 安装
- Oracle数据库学习整理day3
- linux网络详细配置
- 【分治递归法】顺序表应用7:最大子段和之分治递归法
- set-matrix-zeroes
- Codeforces 859D Third Month Insanity 概率DP
- 晓说2017-定期持续更新
- APUE 第3-5章
- [TYVJ]P4869 罪犯分组 状态压缩DP
- PAT-0-1003-我要通过!(20)
- hibernate unknow entity
- Java中的六种数据存储
- 跳台阶