題目地址:
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;
}
}
時間複雜度,空間。