1.7 题目:
编写一个算法,若M*N矩阵中某个元素为0,则将其所在的行和列清零。
解法:
遍历两次矩阵,使用两个布尔数组记录应该被清零的行和列,第一次遍历,记录下需要被清零的。
第二次遍历,清零即可。
- public static void setZeros(int[][] matrix){
- boolean[] rows = new boolean[matrix.length];
- boolean[] columns = new boolean[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){
- rows[i] = true;
- columns[j] = true;
- }
- }
- }
- for(int i=0;i<matrix.length;i++){
- for(int j=0;j<matrix[0].length;j++){
- if(rows[i] || columns[j]){
- matrix[i][j] = 0;
- }
- }
- }
- }
测试用例:
- @Test
- public void test_1_7(){
- int[][] matrix = {{1,0,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
- ArrayUtil.setZeros(matrix);
- for(int i=0;i<4;i++){
- for(int j=0;j<4;j++){
- if(j<3)
- System.out.print(matrix[i][j]+"\t");
- else
- System.out.println(matrix[i][j]);
- }
- }
- }
测试结果:
0 0 0 0
5 0 7 8
9 0 11 12
13 0 15 16