LeetCode 1314. Matrix Block Sum

原题链接在这里:https://leetcode.com/problems/matrix-block-sum/

题目:

Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

  • i - k <= r <= i + k,
  • j - k <= c <= j + k, and
  • (r, c) is a valid position in the matrix.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]

Example 2:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n, k <= 100
  • 1 <= mat[i][j] <= 100

题解:

First have a range sum array nums.

nums[i][j] = mat[i - 1][j - 1] + nums[i][j - 1] + nums[i - 1][j] - nums[i - 1][j - 1]. 

For the block. we would to get the r1, c1, r2, c2.

Then calculate the block value mat[i][j] = nums[r2][c2] - nums[r1][c2] - nums[r2][c1] + nums[r1][c1].

Time Compleixity: O(m * n). m = mat.length. n = mat[0].length.

Space: O(m * n)

AC Java:

 1 class Solution {
 2     public int[][] matrixBlockSum(int[][] mat, int k) {
 3         if(mat == null || mat.length == 0 || mat[0].length == 0){
 4             return mat;
 5         }
 6         
 7         int m = mat.length;
 8         int n = mat[0].length;
 9         int [][] nums = new int[m + 1][n + 1];
10         for(int i = 1; i <= m; i++){
11             for(int j = 1; j <= n; j++){
12                 nums[i][j] = mat[i - 1][j - 1] + nums[i - 1][j] + nums[i][j - 1] - nums[i - 1][j - 1];
13             }
14         }
15         
16         for(int i = 0; i < m; i++){
17             for(int j = 0; j < n; j++){
18                 int r1 = Math.max(0, i - k);
19                 int r2 = Math.min(m, i + k + 1);
20                 int c1 = Math.max(0, j - k);
21                 int c2 = Math.min(n, j + k + 1);
22                 mat[i][j] = nums[r2][c2] - nums[r1][c2] - nums[r2][c1] + nums[r1][c1];
23             }
24         }
25         
26         return mat;
27     }
28 }

类似Range Sum Query 2D - Immutable.

posted @ 2022-06-23 12:14  Dylan_Java_NYC  阅读(28)  评论(0编辑  收藏  举报