前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 308. 二维区域和检索 - 可变(前缀和)

LeetCode 308. 二维区域和检索 - 可变(前缀和)

作者头像
Michael阿明
发布2021-02-19 09:54:40
6090
发布2021-02-19 09:54:40
举报
文章被收录于专栏:Michael阿明学习之路

文章目录

1. 题目

给你一个 2D 矩阵 matrix,请计算出从左上角 (row1, col1) 到右下角 (row2, col2) 组成的矩形中所有元素的和。

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

上述粉色矩形框内的,该矩形由左上角 (row1, col1) = (2, 1) 和右下角 (row2, col2) = (4, 3) 确定。其中,所包括的元素总和 sum = 8。

代码语言:javascript
复制
示例:
给定 matrix = [
  [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]
]
sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
 
注意:
矩阵 matrix 的值只能通过 update 函数来进行修改
你可以默认 update 函数和 sumRegion 函数的调用次数是均匀分布的
你可以默认 row1 ≤ row2,col1 ≤ col2

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/range-sum-query-2d-mutable 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
class NumMatrix {
	vector<vector<int>> mat;
	vector<vector<int>> rowpresum;
public:
    NumMatrix(vector<vector<int>>& matrix) {
    	mat = matrix;
    	rowpresum = matrix;
    	for(int i = 0, j; i < matrix.size(); ++i)
    	{
    		for(j = 1; j < matrix[0].size(); ++j)
    			rowpresum[i][j] = rowpresum[i][j-1] + matrix[i][j];
    	}
    }
    
    void update(int row, int col, int val) {
        mat[row][col] = val;
        rowpresum[row][col] = (col > 0 ? rowpresum[row][col-1] : 0) + val;
    	for(int j = col+1; j < mat[0].size(); ++j)
    		rowpresum[row][j] = rowpresum[row][j-1] + mat[row][j];
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
    	int sum = 0;
    	for(int i = row1; i <= row2; ++i)
    	{
    		sum += rowpresum[i][col2] - (col1==0 ? 0 : rowpresum[i][col1-1]);
    	}
    	return sum;
    }
};

28 ms 12.2 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档