【Lintcode】1840. Matrix restoration

題目地址:

https://www.lintcode.com/problem/matrix-restoration/description

給定某個二維數組的前綴和數組(對於二維數組AA,其前綴和數組爲BB,則B[i][j]=u=0iv=0jA[u][v]B[i][j]=\sum_{u=0}^i\sum_{v=0}^jA[u][v],嚴格意義上不能算前綴和數組,一般前綴和數組要多開一行一列,但已經很相似了),要求返回原數組。

容易看出,對於非第一行和第一列的位置,A[i][j]=B[i][j]B[i1][j]B[i][j1]+B[i1][j1]A[i][j]=B[i][j]-B[i-1][j]-B[i][j-1]+B[i-1][j-1],對於第一行而言A[0][j]=B[0][j]B[0][j1]A[0][j]=B[0][j]-B[0][j-1],對於第一列而言A[i][0]=B[i][0]B[i1][0]A[i][0]=B[i][0]-B[i-1][0],而A[0][0]=B[0][0]A[0][0]=B[0][0]。爲了節省空間,我們可以直接在給定的數組上操作,這樣的話需要從右下角向左上角更新。代碼如下:

public class Solution {
    /**
     * @param n: the row of the matrix
     * @param m: the column of the matrix
     * @param after: the matrix
     * @return: restore the matrix
     */
    public int[][] matrixRestoration(int n, int m, int[][] after) {
        // write your code here
        for (int i = n - 1; i > 0; i--) {
            for (int j = m - 1; j > 0; j--) {
                after[i][j] = after[i][j] - after[i - 1][j] - after[i][j - 1] + after[i - 1][j - 1];
            }
        }
    
        for (int i = n - 1; i > 0; i--) {
            after[i][0] -= after[i - 1][0];
        }
    
        for (int i = m - 1; i > 0; i--) {
            after[0][i] -= after[0][i - 1];
        }
        
        return after;
    }
}

時間複雜度O(mn)O(mn),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章