【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)

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