0
点赞
收藏
分享

微信扫一扫

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

绣文字 2022-02-07 阅读 53
leetcode

在这里插入图片描述
在这里插入图片描述

class NumMatrix {
    int m;
    int n;
    int[][] preSum;
    public NumMatrix(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        preSum = new int[m][n];
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                int left = inArea(i,j-1) == true ? preSum[i][j-1]:0;
                int up = inArea(i-1,j) == true ? preSum[i-1][j]:0;
                int leftup = inArea(i-1,j-1) == true ? preSum[i-1][j-1]:0;
                preSum[i][j] = left + up - leftup + matrix[i][j];
            }
        }
    }
    public boolean inArea(int x,int y){
        return x >= 0 && x < m && y >= 0 && y < n;
    }
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int left = inArea(row2,col1-1) == true ? preSum[row2][col1-1]:0;
        int up = inArea(row1-1,col2) == true ? preSum[row1-1][col2]:0;
        int leftup = inArea(row1-1,col1-1) == true ? preSum[row1-1][col1-1]:0;
        return preSum[row2][col2] - left - up + leftup;
    }
}
举报

相关推荐

0 条评论