题目地址:
https://www.lintcode.com/problem/matrix-restoration/description
给定某个二维数组的前缀和数组(对于二维数组,其前缀和数组为,则,严格意义上不能算前缀和数组,一般前缀和数组要多开一行一列,但已经很相似了),要求返回原数组。
容易看出,对于非第一行和第一列的位置,,对于第一行而言,对于第一列而言,而。为了节省空间,我们可以直接在给定的数组上操作,这样的话需要从右下角向左上角更新。代码如下:
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;
}
}
时间复杂度,空间。