2021년 8월 14일 토요일

Leetcode 15th August

Leetcode 15th August

Leetcode 15th August

Set Matrix Zeroes

이 문제는 matrix 가 주워졌을때 cell 중에 0 이포함되어있으면 그 해당 rows, cols의 값을 0으로 변경하는 문제 입니다.
This question is Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix.

그래서 저의 경우 rows, cols sets를 만든 다음에 matrix[i][j] 값이 0 일 경우 rows 에 i, cols에 j를 추가하고, 그담에 loop를 통해서 i가 rows 에 포함되어있거나 cols 가 j에 포함되어있을 경우 값을 0으로 변경하는 방식으로 해결했습니다.

For solving this problem i create two sets named rows, cols and add i in rows and j in cols if the cell value is 0, after set up rows, cols values, set matrix value 0 if i value in rows or j value in cols

Python

Time complexity: O(M * N)

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        m = len(matrix[0])
        res = [['x'] * m for _ in range(n)]
        
        rows = set()
        cols = set()
        for i in range(n):
            for j in range(m):
                if matrix[i][j] == 0:
                    rows.add(i)
                    cols.add(j)
        for i in range(n):
            for j in range(m):
                if i in rows or j in cols:
                    matrix[i][j] = 0

댓글 없음:

댓글 쓰기