leetcode(304) Range Sum Query 2D - Immutable

来源:互联网 发布:line是什么聊天软件 编辑:程序博客网 时间:2024/05/17 07:08

题目链接:https://leetcode.com/problems/range-sum-query-2d-immutable/

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [  [3, 0, 1, 4, 2],  [5, 6, 3, 2, 1],  [1, 2, 0, 1, 5],  [4, 1, 0, 1, 7],  [1, 0, 3, 0, 5]]sumRegion(2, 1, 4, 3) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12
求sum数组,sum数组是给出数组的从0行0列到i行j列的所有数和的一个数组

sumRegion方法只对sum数组进行计算,得出结果。

公式总结:

sums[i][j] = matrix[i-1][j-1] + sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1];

返回结果:sums[r2][c2] + sums[r1][c1] - sums[r2][c1] - sums[r1][c2];

java代码(包含测试):

package leetcode;public class NumMatrix {int sums[][];public NumMatrix(int[][] matrix) {if (matrix == null) {return;}int n = matrix.length; // 行数System.out.println(n + "");if (n == 0) {return;}int m=matrix[0].length;//列数sums = new int[n+1][m+1];for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {sums[i][j] = matrix[i-1][j-1] + sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1];}}}public int sumRegion(int row1, int col1, int row2, int col2) {row2++;col2++;return sums[row2][col2] + sums[row1][col1] - sums[row1][col2] - sums[row2][col1];}public static void main(String[] args) {// TODO Auto-generated method stubint[][] matrix = { { 3, 0, 1, 4, 2 }, { 5, 6, 3, 2, 1 }, { 1, 2, 0, 1, 5 }, { 4, 1, 0, 1, 7 },{ 1, 0, 3, 0, 5 } };NumMatrix numMatrix = new NumMatrix(matrix);System.out.println(numMatrix.sumRegion(2, 1, 4, 3)+"");}}
这里说明以下为什么sums行数列数设置为n+1和m+1.由于如果对边缘进行加减,比如求(1,1)到(0,0)之间的点,发现边界外并没有数字可以进行运算,所以sums多出来一行一列也就是上边沿和左边沿赋值为0,这样就可以进行数字运算了。所以对应matrix[0][0]点的和就是matrix[0][0]+sums[0][1]+sums[1][0]-sum[0][0]=matrix[0][0]+0+0-0,这样的计算结果才是正确的。

0 0
原创粉丝点击