leetcode(304) Range Sum Query 2D - Immutable

本文详细介绍了二维矩阵区间和查询算法的实现原理及应用,包括如何通过前缀和数组优化查询效率,并通过实例代码演示了算法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: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) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(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 stub
		int[][] 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,这样的计算结果才是正确的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值