阅读 44

LeetCode刷题(九)

零矩阵

编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。

示例 1:

输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
示例 2:

输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]

解题思路:
开辟两个一维数组存放要清理的行列,先遍历一遍,保存需要清理的行列,然后在遍历修改,如果可以使用二维数组也可以先读取原数组需要修改的地方,在新的数组上修改,
java

class Solution {
    public void setZeroes(int[][] matrix) {
        boolean[] line = new boolean[matrix.length];
        boolean[] column = 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) {
                    line[i] = true;
                    column[j] = true;
                }
            }
        }
        
        // 开始对行清零
        for (int i = 0; i < matrix.length; i++) {
            if (line[i]) {
                for (int j = 0; j < matrix[0].length; j++) {
                    matrix[i][j] = 0;
                }
            }
        }

        // 开始对列清零
        for (int i = 0; i < matrix[0].length; i++) {
            if (column[i]) {
                for (int j = 0; j < matrix.length; j++) {
                    matrix[j][i] = 0;
                }
            }
        }

    }
}
复制代码

python

import copy
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        res_x=[]
        res_y=[]
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j]==0:
                    res_x.append(i)
                    res_y.append(j)
        for math in range(len(res_x)):
            for x in res_x:
                for m in range(len(matrix[0])):
                    matrix[x][m]=0
            for y in res_y:
                for n in range(len(matrix)):
                    matrix[n][y]=0
        return matrix
        # res=copy.deepcopy(matrix)
        # for i in range(len(matrix)):
        #     for j in range(len(matrix[0])):
        #         if matrix[i][j]==0:
        #             for x in range(len(matrix)):
        #                 res[x][j]=0
        #                 print(res[x][j])
        #             for y in range(len(matrix[0])):
        #                 res[i][y]=0
        # return res
复制代码
文章分类
后端
文章标签