[leetcode]Set Matrix Zeroes
2014-07-17 16:56
176 查看
Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.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(mn)
算法:
思路1. 空间复杂度O(mn)
开辟O(m*n)空间tag,标记matrix中每个0的位置,全部标记完之后,再遍历tag,将matrix相关行列赋0
public class Solution { public void setZeroes(int[][] matrix) { if(matrix == null || matrix.length == 0) return; int height = matrix.length; int width = matrix[0].length; boolean hasZeroInFirstRow = false; for(int j = 0; j < width; j++){ if(matrix[0][j] == 0) hasZeroInFirstRow = true; } for(int i = 1; i < height; i++){ boolean hasZero = false; for(int j = 0; j < width; j++){ if(matrix[i][j] == 0){ hasZero = true; matrix[0][j] = 0; } } if(hasZero) for(int j = 0; j < width; matrix[i][j++] = 0); } for(int j = 0; j < width; j++){ if(matrix[0][j] == 0){ for(int i = 0; i < height; matrix[i++][j] = 0); } } if(hasZeroInFirstRow) for(int j = 0; j < width; matrix[0][j++] = 0); } }
View Code
以上四种算法的时间复杂度都是O(m*n),空间复杂度从O(m*n)到O(1),可能代码写的不够简洁,但是可读性应该还好吧,哈哈。FYI
相关文章推荐
- [LeetCode] Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- 【LeetCode】(73)Set Matrix Zeroes(Medium)
- [leetcode] 73. Set Matrix Zeroes 解题报告
- [LeetCode] 73. Set Matrix Zeroes
- leetcode--set_matrix_zeroes
- leetcode 073 —— Set Matrix Zeroes
- leetcode — set-matrix-zeroes
- [leetcode]Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [算法分析与设计] leetcode 每周一题: Set Matrix Zeroes
- Set Matrix Zeroes - LeetCode 73
- 【leetcode】Set Matrix Zeroes
- leetcode JAVA Set Matrix Zeroes 难度系数3 3.24
- [leetcode] Set Matrix Zeroes
- 【Leetcode】【python】Set Matrix Zeroes
- Set Matrix Zeroes -- leetcode
- leetcode Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode Set Matrix Zeroes