【LeetCode每天一題】Set Matrix Zeroes(設置0矩陣)
阿新 • • 發佈:2019-04-27
矩陣 forward 參考答案 -m out 最簡 .com 設置 entire
這道題最簡單的就是使用O(m*n)的空間來解決問題,但是空間浪費太高。我們可以先對矩陣進行遍歷,將0出現的位置的行坐標和列坐標分別記錄下來。然後當遍歷完畢之後我們根據行坐標和列坐標來設置0.得到最後的結果。時間復雜度為O(m*n), 空間復雜度為O(m+n)。 另外在題中,提到使用O(1)的空間也可以解決問題,我沒能想出來,看了參考答案之後明白了他在遇到元素0的時候,先將該元素所對應的行的第一個元素和對應列的第一個元素設置為0,然後遍歷結束之後判斷首行元素的的值狀態將剩余的部分設置為0.最後得到結果。
解決代碼
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
Follow up:
- A straight forward solution using O(mn) space is probably a bad idea.
- A simple improvement uses O(m + n) space, but still not the best solution.
- Could you devise a constant space solution?
這道題最簡單的就是使用O(m*n)的空間來解決問題,但是空間浪費太高。我們可以先對矩陣進行遍歷,將0出現的位置的行坐標和列坐標分別記錄下來。然後當遍歷完畢之後我們根據行坐標和列坐標來設置0.得到最後的結果。時間復雜度為O(m*n), 空間復雜度為O(m+n)。 另外在題中,提到使用O(1)的空間也可以解決問題,我沒能想出來,看了參考答案之後明白了他在遇到元素0的時候,先將該元素所對應的行的第一個元素和對應列的第一個元素設置為0,然後遍歷結束之後判斷首行元素的的值狀態將剩余的部分設置為0.最後得到結果。
1 class Solution(object):
2 def setZeroes(self, matrix):
3 """
4 :type matrix: List[List[int]]
5 :rtype: None Do not return anything, modify matrix in-place instead.
6 """
7 if not matrix:
8 return matrix
9 row, cloum = len(matrix), len(matrix[0])
10 tem_row, tem_cloum = set(), set()
11 for i in range(row): #遍歷矩陣得到0的行坐標和列左邊
12 for j in range(cloum):
13 if matrix[i][j] == 0:
14 tem_row.add(i)
15 tem_cloum.add(j)
16 self.set_zero(matrix, tem_row, tem_cloum) # 進行0設置
17
22 def set_zero(self, matrix, tem_row, tem_cloum):
23 for row in tem_row: # 設置列
24 for i in range(len(matrix[0])):
25 if matrix[row][i] != 0:
26 matrix[row][i] = 0
27 for cloum in tem_cloum: # 設置行
28 for j in range(len(matrix)):
29 if matrix[j][cloum] != 0:
30 matrix[j][cloum] = 0
常量空間的解法
詳細解釋鏈接:https://leetcode.com/problems/set-matrix-zeroes/solution/
1 class Solution(object):
2 def setZeroes(self, matrix):
3 """
4 :type matrix: List[List[int]]
5 :rtype: void Do not return anything, modify matrix in-place instead.
6 """
7 is_col = False
8 R = len(matrix)
9 C = len(matrix[0])
10 for i in range(R): # 遍歷矩陣,得到元素為0的地址,並設置該列和該行起始位置為0,
11 if matrix[i][0] == 0:
12 is_col = True
13 for j in range(1, C):
14 if matrix[i][j] == 0:
15 matrix[0][j] = 0
16 matrix[i][0] = 0
17
18
19 for i in range(1, R): # 根據行的開頭和列的開頭來設置剩余部分的元素值
20 for j in range(1, C):
21 if not matrix[i][0] or not matrix[0][j]:
22 matrix[i][j] = 0
23
24 if matrix[0][0] == 0: # 判斷起始位置是否為0
25 for j in range(C):
26 matrix[0][j] = 0
27
28 if is_col: # 第一列全為0
29 for i in range(R):
30 matrix[i][0] = 0
【LeetCode每天一題】Set Matrix Zeroes(設置0矩陣)