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
}
相关推荐
NAGNIP11 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队12 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja17 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下17 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶17 小时前
算法 --- 字符串
算法
博笙困了17 小时前
AcWing学习——差分
c++·算法
NAGNIP17 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP17 小时前
大模型微调框架之LLaMA Factory
算法
echoarts17 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客17 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法