Cracking the coding interview--Q1.7
2014-01-26 23:39
274 查看
题目
原文:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
译文:
写一个算法使一个MxN的矩阵中出现0的元素的行和列都设为0.
解答
遍历一遍矩阵,将出现0的元素用两个数组将其行列号存储下来,或开一个行数组row和列数组col,当元素a[i][j]等于0时, 就把row[i]和col[j]置为true,第二次遍历的时候,将对应的行列号置为0即可,下面的两种写法:
如有更好方法,还望交流!
---EOF---
原文:
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
译文:
写一个算法使一个MxN的矩阵中出现0的元素的行和列都设为0.
解答
遍历一遍矩阵,将出现0的元素用两个数组将其行列号存储下来,或开一个行数组row和列数组col,当元素a[i][j]等于0时, 就把row[i]和col[j]置为true,第二次遍历的时候,将对应的行列号置为0即可,下面的两种写法:
class Q1_7{ public static void setZero(int[][] matrix){ //存储元素为0的位置的行列号 int[] row=new int[matrix.length]; int[] column=new int[matrix[0].length]; int k=0,l=0; for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ if(matrix[i][j]==0){ row[k++]=i; column[l++]=j; } } } for(int i=0;i<row.length;i++){ for(int j=0;j<matrix[0].length;j++){ matrix[row[i]][j]=0; } } for(int i=0;i<column.length;i++){ for(int j=0;j<matrix.length;j++){ matrix[j][column[i]]=0; } } } //另一种写法 public static void setZeros(int[][] matrix){ int[] row=new int[matrix.length]; int[] column=new int[matrix[0].length]; for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ if(matrix[i][j]==0){ row[i]=1; column[j]=1; } } } for(int i=0;i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ if(row[i]==1||column[j]==1){ matrix[i][j]=0; } } } } public static void main(String[] args){ int[][] a={ {1,2,0,4}, {0,3,9,5}, {4,6,8,3} }; //setZero(a); setZeros(a); for(int i=0;i<3;i++){ int j; for(j=0;j<3;j++) System.out.printf(a[i][j]+","); System.out.println(a[i][j]); } } }
如有更好方法,还望交流!
---EOF---
相关文章推荐
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q1.7
- Cracking the coding interview--Q1.7
- Cracking The Coding Interview 1.5
- Cracking the coding interview--Q17.4
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q20.4
- Cracking the coding interview--Q20.13
- Cracking the Coding Interview 题目分析笔记—— Array and String
- 《Cracking the Coding Interview》——第17章:普通题——题目9
- Cracking the coding interview--Q5.7
- 《Cracking the Coding Interview》——第18章:难题——题目9
- Cracking The Coding Interview 3rd -- 1.3
- Cracking the coding interview--Q2.2
- [Cracking the Coding Interview] Chapter 1 - Arrays and Strings
- Cracking the coding interview--Q8.1
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q8