網頁

2024年7月20日 星期六

Python C++採Greedy 2 pointers解Leetcode 1605 Find Valid Matrix Given Row ...


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.
[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
        

沒有留言:

張貼留言

HTML 編輯器