LeetCode-304. 二维区域和检索 - 矩阵不可变-Java-medium

题目链接

法一(二维前缀和)
/**
 * 法一(二维前缀和)
 * (1)presum[i][j]表示从[0][0]到[i][j]位置的子矩阵所有元素之和
 * (2)presum矩阵要比原矩阵多一行一列,是为了让第0行与第0列的元素也能使用递推公式
 * (3)可以利用presum求子矩阵的面积
 */
public class Solution304 {

    /**
     * 二维前缀和矩阵
     */
    private int[][] presum;

    /**
     * 初始化二维前缀和矩阵presum
     *
     * @param matrix
     */
    public Solution304(int[][] matrix) {
        int rowSize = matrix.length, colSize = matrix[0].length;
        this.presum = new int[rowSize + 1][colSize + 1];
        for (int row = 0; row < rowSize; row++) {
            for (int col = 0; col < colSize; col++) {
                presum[row + 1][col + 1] = presum[row + 1][col] + presum[row][col + 1] - presum[row][col] + matrix[row][col];
            }
        }
    }

    /**
     * 利用presum返回左上角(row1, col1)、右下角(row2, col2)所描述的子矩阵的元素总和
     *
     * @param row1
     * @param col1
     * @param row2
     * @param col2
     * @return
     */
    public int sumRegion(int row1, int col1, int row2, int col2) {
        return presum[row2 + 1][col2 + 1] - presum[row2 + 1][col1] - presum[row1][col2 + 1] + presum[row1][col1];
    }
    
}
本地测试
        /**
         * 304. 二维区域和检索 - 矩阵不可变
         */
        lay.showTitle(304);
        int[][] matrix304 = new int[][]{{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}};
        arrayOpt.showIntTwoDimArray(matrix304, matrix304.length);
        Solution304 sol304 = new Solution304(matrix304);
        System.out.println(sol304.sumRegion(2, 1, 4, 3));
        System.out.println(sol304.sumRegion(1, 1, 2, 2));
        System.out.println(sol304.sumRegion(1, 2, 2, 4));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值