Python CPP採Greedy 2pointers解Leetcode 1605 Find Valid Matrix Given Row and Column Sums
將大小為 r*c 的陣列 arr 初始化為全 0
獨立的 i、j 是 2 個指標。使用迴圈繼續
設 x=min(rowSum[i], colSum[j])
設定 arr[i][j]=x & rowSum[i]-=x, colSum[j]-=x 根據 rowSum[i]==0 & colSum[j]==0 移動 i, j。
[Python解請進]
Initialize array arr of size r*c with all 0
indies i, j are the 2 pointers. Use a loop to proceed
Let x=min(rowSum[i], colSum[j])
Set arr[i][j]=x & rowSum[i]-=x, colSum[j]-=x move i, j depending on rowSum[i]==0 & colSum[j]==0.
[codes on Leetcode]https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/solutions/5503406/greedy-matrix-with-2-pointers-23ms-beats-99-32/
[Python C++集合論Cantor對角線法解Leetcode 1980 Find Unique Binary String]https://www.youtube.com/watch?v=0iFR8nafMWE
class Solution: def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: r, c=len(rowSum), len(colSum) arr=[[0]*c for _ in range(r)] i, j=0, 0 while i<r and j<c: x=min(rowSum[i], colSum[j]) arr[i][j]=x rowSum[i]-=x colSum[j]-=x i+=(rowSum[i]==0) j+=(colSum[j]==0) return arr
沒有留言:
張貼留言