问题
问题:给定一个二维数组,给定一个矩形框的左上角坐标(a1,a2),右下角坐标(b1,b2),计算该区域内数字之和。
解题思路
O(1) * (row2 - row1 + 1) * (col2 - col1 + 1);
数组已经是常数访问时间了,还有什么花哨的玩法么
代码
class NumMatrix {
private int[][] matrix;
public NumMatrix(int[][] matrix) {
this.matrix = matrix;
}
public NumMatrix(){}
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
int[] temp;
for(int i = row1; i <= row2;i++){
temp = matrix[i];
for(int j = col1;j <= col2;j++){
sum += temp[j];
}
}
return sum;
}
}