11-数组-二维区域和检索 - 矩阵不可变

这是数组的第11篇算法,力扣链接

给定一个二维矩阵 matrix,以下类型的多个请求:

  • 计算其子矩形范围内元素的总和,该子矩阵的 左上角(row1, col1)右下角(row2, col2)

实现 NumMatrix 类:

  • NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行初始化
  • int sumRegion(int row1, int col1, int row2, int col2) 返回 左上角 (row1, col1)右下角 (row2, col2) 所描述的子矩阵的元素 总和

示例 1:

复制代码
输入: 
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[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]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
输出: 
[null, 8, 11, 12]

解释:
NumMatrix numMatrix = new NumMatrix([[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.sumRegion(2, 1, 4, 3); // return 8 (红色矩形框的元素总和)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (绿色矩形框的元素总和)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和)

这道题其实就是看着吓人,其实在我们自维护的type里面维护一个横/纵坐标的和的列表即可。

Go 复制代码
type NumMatrix struct {
	sumHeight [][]int
}

func Constructor(matrix [][]int) NumMatrix {
	sumHeight := make([][]int, len(matrix))
	for ri, row := range matrix {
		if sumHeight[ri] == nil {
			sumHeight[ri] = make([]int, len(matrix[0]))
		}
		for ci, col := range row {
			if ri == 0 {
				sumHeight[ri][ci] = col
			} else {
				sumHeight[ri][ci] = col + sumHeight[ri-1][ci]
			}
		}
	}
	return NumMatrix{
		sumHeight: sumHeight,
	}
}

func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
	result := 0
	for i := col1; i <= col2; i++ {
		if row1 == 0 {
			result += this.sumHeight[row2][i]
		} else {
			result += this.sumHeight[row2][i] - this.sumHeight[row1-1][i]
		}
	}
	return result
}
相关推荐
人道领域1 天前
【LeetCode刷题日记】454:四数相加Ⅱ
算法·leetcode
她说彩礼65万1 天前
C语言 指针运算
c语言·数据结构·算法
skilllite作者1 天前
自进化 Agent 的 skills 别长成烟囱:从多入口分叉到统一发现与 spec 防火带
人工智能·算法·rust·openclaw·agentskills
kaikaile19951 天前
移动机器人路径跟踪的设计与仿真:模型预测控制(MPC)详解
人工智能·stm32·嵌入式硬件·算法
进击的荆棘1 天前
递归、搜索与回溯——递归
算法·leetcode·递归
2301_822703201 天前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_764441331 天前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI1 天前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法