zoukankan      html  css  js  c++  java
  • 【leetcode】1314. Matrix Block Sum

    题目如下:

    Given a m * 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

    解题思路:记grid[i][j] 为 左上角顶点是(0,0),右下角顶点是(i,j) 的矩阵和,grid可以通过时间复杂度为O(n^2)的循环计算出来,接下来再遍历mat,计算出相应每个子矩阵和即可。

    代码如下:

    class Solution(object):
        def matrixBlockSum(self, mat, K):
            """
            :type mat: List[List[int]]
            :type K: int
            :rtype: List[List[int]]
            """
            res = [[0] * len(mat[0]) for _ in mat]
            grid = [[0] * len(mat[0]) for _ in mat]
            for i in range(len(mat)):
                count = 0
                for j in range(len(mat[0])):
                    count += mat[i][j]
                    grid[i][j] = count
    
            for i in range(len(res)):
                for j in range(len(res[i])):
                    left = max(0,j-K)
                    right = min(j+K,len(res[i])-1)
                    count = 0
                    for row in range(max(0,i-K),min(i+K+1,len(res))):
                        if left == 0:
                            count += grid[row][right]
                        else:
                            count += (grid[row][right] - grid[row][left-1])
                    res[i][j] = count
            return res
            
  • 相关阅读:
    3. 尾缀
    Cocos工程命名规则整理(node部分)
    3.1-3.3 HBase Shell创建表
    2.11-2.12 HBase的数据迁移常见方式
    2.8-2.10 HBase集成MapReduce
    2.7 HBase架构深入剖析
    2.3-2.6 HBase java API
    2.1-2.2 HBase数据存储
    1.6-1.8 HBase表的物理模型
    1.4-1.5 HBase部署及基本使用
  • 原文地址:https://www.cnblogs.com/seyjs/p/12183197.html
Copyright © 2011-2022 走看看