Cracking coding interview(1.7) 设置某个位置为零的矩阵对应行列均为0
2014-07-26 17:14
435 查看
1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
当前较优解
最坏情况下:
时间复杂度:O(m*n)
空间复杂度:O(m+n)
import java.util.ArrayList; public class Solution{ //time complexity:O(m*n), space complexity:O(m+n)(worst complexity) public static void setMatrix(int[][] M){ int[] c = new int[M.length];// //record row or col need to be set with 0 //space complexty:O(m+n) ArrayList<Integer> row = new ArrayList<Integer>(); ArrayList<Integer> col = new ArrayList<Integer>(); //time complexity:O(m*n) for(int i=0;i < M.length;i++) for(int j=0;j < M[i].length;j++){ if(M[i][j] != 0) continue; if(!row.contains(i)) row.add(i); if(!col.contains(j)) col.add(j); } //time complexity:O(m*n) //set row with 0 int index = 0; for(int i=0;i < row.size();i++){ index = row.get(i); for(int j=0;j < M[index].length;j++) M[index][j] = 0; } //time complexity:O(n*m) //set column with 0 for(int i=0;i < col.size();i++){ index = col.get(i); for(int j=0;j < M.length;j++) M[j][index] = 0; } } private static void printM(int[][] M){ for(int i=0;i < M.length;i++){ for(int j=0;j < M[i].length;j++) System.out.print(M[i][j]+" "); System.out.println(); } } public static void main(String[] args){ int[][] M = new int[][]{ {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, }; Solution.printM(M); Solution.setMatrix(M); System.out.println();// Solution.printM(M); } }
当前较优解
最坏情况下:
时间复杂度:O(m*n)
空间复杂度:O(m+n)
相关文章推荐
- Cracking The Coding Interview 1.7
- 【Cracking the coding interview】Q1.7(矩阵置0)
- cracking the coding interview No1.7
- Cracking the coding interview--Q1.3
- cracking the coding interview problem solution 1.5
- 二维数组中的查找 Cracking the coding interview 9.6
- 判断一个二叉树是否是平衡二叉树 Cracking the coding interview 4.1
- 把矩阵0元所在行列设置为0
- Cracking the coding interview--Q1.2
- Cracking the coding interview--Q9.3
- cracking the coding interview problem solution 1.3
- Cracking The Coding Interview 5th 完整版
- WindowsXP相关设置对应的注册表位置
- Cracking the coding interview--问题与解答
- Cracking the coding interview--Q1.1(python的位操作)
- cracking the coding interview problem solution 1.8
- 定位“某项操作”在“注册表”中对应的位置与设置
- WindowsXP相关设置对应的注册表位置
- Cracking the Coding Interview
- 技术面试圣经《Cracking the Coding Interview》题解C++版