LeetCode_OJ【73】Set Matrix Zeroes
来源:互联网 发布:手机短信淘宝链接 编辑:程序博客网 时间:2024/05/16 19:03
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.
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?
给定一个矩阵,如果矩阵中某个元素为0,则与该元素同行同列的元素都将置为0. 要求算法位原地算法(空间复杂度为O(1)).
按照提示,一开始可以复制一个矩阵,对照复制的矩阵的每个元素对原来的矩阵进行操作,但是这样需要O(mn)的额外空间。
然后想到只需要记录哪些行和列需要置0,先遍历一遍矩阵,得到需要置0的行和列,然后再对矩阵进行操作,这样需要O(m + n)的空间记录这些行和列。
仔细想一下,其实这些信息可以直接记录在矩阵的第一行和第一列。先遍历一遍矩阵,如果i行需要置0,则设置matrix[i][0]为0,如果j列需要置0,则matrix[0][j]为0.
然后根据第一行第一列再对矩阵操作。
不过在实现这个思路的时候需要小心。
首先,需要两个额外空间记录第一行和第一列是否需要置0;
由于其他行和列在置0的时候,需要参照第一行第一列,所以第一行第一列在其他行列重置时不能改变。
处理完其他行列后再根据设置的两个额外空间处理第一行第一列。
JAVA实现如下:
public class Solution { public void setZeroes(int[][] matrix) { int x = 1 , y = 1; //看第一行和第一列是否出现值为0的元素 for(int i = 0 ; i < matrix.length ; i ++) if(matrix[i][0] == 0) y = 0; for(int j = 0 ; j < matrix[0].length ; j ++) if(matrix[0][j] == 0) x = 0; //遍历其他行和列,并将信息记录在第一行第一列for(int i = 1 ; i < matrix.length ; i ++){for(int j = 1 ; j < matrix[0].length ; j ++ ){if(matrix[i][j] == 0){matrix[i][0] = 0;matrix[0][j] = 0;}}}//根据第一行第一列的值是否为0,将矩阵其他行其他列的元素置0for(int i = 1 ; i < matrix.length ; i ++){for(int j = 1 ; j < matrix[0].length ; j ++ ){if(matrix[i][0] == 0 || matrix[0][j] == 0){matrix[i][j] = 0;}}}//设置第一行和第一列。if(x == 0) for(int j = 0 ; j < matrix[0].length ; j ++) matrix[0][j] = 0;if(y == 0) for(int i = 0 ; i < matrix.length ; i ++) matrix[i][0] = 0; }}
- LeetCode_OJ【73】Set Matrix Zeroes
- 73Set Matrix Zeroes
- [73]Set Matrix Zeroes
- LeetCode 73: Set Matrix Zeroes
- LeetCode(73)Set Matrix Zeroes
- LeetCode 73 Set Matrix Zeroes
- [leetcode 73] Set Matrix Zeroes
- [LeetCode 73]Set Matrix Zeroes
- leetcode-73 Set Matrix Zeroes
- leetcode || 73、Set Matrix Zeroes
- Set Matrix Zeroes - LeetCode 73
- LeetCode---(73) Set Matrix Zeroes
- LeetCode(73) Set Matrix Zeroes
- Leetcode# 73 Set Matrix Zeroes
- leetcode 73: Set Matrix Zeroes
- Leetcode#73||Set Matrix Zeroes
- 【leetcode】【73】Set Matrix Zeroes
- 【LeetCode-73】Set Matrix Zeroes
- 双线性插值算法的详细总结
- LeetCode[Math]----Excel Sheet Column Title----Excel Sheet Column Number
- 网页中控件绑定数据源小demo
- PAT (Basic Level) Practise (中文)1033. 旧键盘打字(20)
- MySQL导出和导入含有二进制字段的数据
- LeetCode_OJ【73】Set Matrix Zeroes
- Linux下tmpfs与ramfs的区别
- 使用Xcode和Instruments调试解决iOS内存泄露
- 百度面试题-乘法表
- 记录一篇有用的文章
- php接受restful api设计中的delete put的接收方式
- 多线程一
- 工厂设计模式
- BSTR用法详解