mirror of
https://github.com/devenperez/leetcode.git
synced 2026-06-15 01:07:07 +00:00
Time: 3 ms (71.33%), Space: 18.6 MB (17.59%) - LeetHub
This commit is contained in:
@@ -5,21 +5,59 @@ class Solution:
|
|||||||
"""
|
"""
|
||||||
# Total complexities:
|
# Total complexities:
|
||||||
# O(mn) time
|
# O(mn) time
|
||||||
# O(m+n) space
|
# O(1) space
|
||||||
|
|
||||||
# O(m+n) space
|
# Prepare first row/col for marking
|
||||||
rowsToZero = set()
|
firstEntry = matrix[0][0]
|
||||||
colsToZero = set()
|
# - use m[0][0] as indicator for first row and col
|
||||||
|
NO_ZEROES_IN_FIRST_ROW_OR_COL = 1
|
||||||
|
ZERO_IN_FIRST_ROW = 2
|
||||||
|
ZERO_IN_FIRST_COL = 3
|
||||||
|
ZERO_IN_FIRST_ROW_AND_COL = 4
|
||||||
|
|
||||||
# Find all zeros - O(mn)
|
matrix[0][0] = NO_ZEROES_IN_FIRST_ROW_OR_COL
|
||||||
for i in range(len(matrix)):
|
if firstEntry == 0:
|
||||||
for j in range(len(matrix[i])):
|
matrix[0][0] = ZERO_IN_FIRST_ROW_AND_COL
|
||||||
|
else:
|
||||||
|
print(f"cp0")
|
||||||
|
# Search first col for 0s - O(n)
|
||||||
|
for i in range(1, len(matrix)):
|
||||||
|
print(f"cp1")
|
||||||
|
if matrix[i][0] == 0:
|
||||||
|
matrix[0][0] = ZERO_IN_FIRST_COL
|
||||||
|
break
|
||||||
|
|
||||||
|
# Search first row for 0s - O(m)
|
||||||
|
for j in range(1, len(matrix[0])):
|
||||||
|
if matrix[0][j] == 0:
|
||||||
|
if matrix[0][0] == ZERO_IN_FIRST_COL:
|
||||||
|
matrix[0][0] = ZERO_IN_FIRST_ROW_AND_COL
|
||||||
|
else:
|
||||||
|
matrix[0][0] = ZERO_IN_FIRST_ROW
|
||||||
|
break
|
||||||
|
|
||||||
|
# Find all zeros outside the first row/col - O(mn)
|
||||||
|
for i in range(1, len(matrix)):
|
||||||
|
for j in range(1, len(matrix[i])):
|
||||||
if matrix[i][j] == 0:
|
if matrix[i][j] == 0:
|
||||||
rowsToZero.add(i)
|
# Use the first row/col as markers
|
||||||
colsToZero.add(j)
|
matrix[i][0] = 0
|
||||||
|
matrix[0][j] = 0
|
||||||
|
|
||||||
# Zero rows and cols as needed - O(mn)
|
# Zero center as needed - O(mn)
|
||||||
for i in range(len(matrix)):
|
for i in range(1, len(matrix)):
|
||||||
for j in range(len(matrix[i])):
|
for j in range(1, len(matrix[i])):
|
||||||
if i in rowsToZero or j in colsToZero:
|
if matrix[i][0] == 0 or matrix[0][j] == 0:
|
||||||
matrix[i][j] = 0
|
matrix[i][j] = 0
|
||||||
|
|
||||||
|
# Set first row/col if needed
|
||||||
|
if matrix[0][0] == ZERO_IN_FIRST_ROW or matrix[0][0] == ZERO_IN_FIRST_ROW_AND_COL:
|
||||||
|
for j in range(1, len(matrix[0])):
|
||||||
|
matrix[0][j] = 0
|
||||||
|
|
||||||
|
if matrix[0][0] == ZERO_IN_FIRST_COL or matrix[0][0] == ZERO_IN_FIRST_ROW_AND_COL:
|
||||||
|
for i in range(1, len(matrix)):
|
||||||
|
matrix[i][0] = 0
|
||||||
|
|
||||||
|
|
||||||
|
matrix[0][0] = firstEntry if matrix[0][0] == NO_ZEROES_IN_FIRST_ROW_OR_COL else 0
|
||||||
Reference in New Issue
Block a user