My code:
public class NumMatrix {
int[][] sum;
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int row = matrix.length;
int col = matrix[0].length;
sum = new int[row][col];
for (int i = 0; i < row; i++) {
sum[i][0] = matrix[i][0];
for (int j = 1; j < col; j++) {
sum[i][j] = sum[i][j - 1] + matrix[i][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int ret = 0;
for (int i = row1; i <= row2; i++) {
int sum1 = (col1 == 0 ? 0 : sum[i][col1 - 1]);
ret += sum[i][col2] - sum1;
}
return ret;
}
}
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
我的复杂度还是很高, 有 O(n)
看了答案,发现有 O(1) 的做法:
My code:
public class NumMatrix {
int[][] sum;
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int row = matrix.length;
int col = matrix[0].length;
sum = new int[row][col];
int total = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
total += matrix[i][j];
sum[i][j] = total;
if (i - 1 >= 0) {
sum[i][j] += sum[i - 1][j];
}
}
total = 0;
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int part1 = 0;
if (col1 - 1 >= 0 && row1 - 1 >= 0) {
part1 = sum[row1 - 1][col1 - 1];
}
int part2 = 0;
if (col1 - 1 >= 0) {
part2 = sum[row2][col1 - 1];
}
int part3 = 0;
if (row1 - 1 >= 0) {
part3 = sum[row1 - 1][col2];
}
return sum[row2][col2] + part1 - part2 - part3;
}
}
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
reference:
https://leetcode.com/articles/range-sum-query-2d-immutable/
不知道怎么就没想出来。。。
记得同学面google就碰到了这道题目。
其实想想,这道题目挺温和的,也算是原题。
如果考虑空间,那么就直接硬算,提高时间复杂度。
如果考虑时间,需要实时,那么就牺牲空间。
Anyway, Good luck, Richardo! -- 08/21/2016