Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).


The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given 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
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

题解:

二维的情况和一维的思路类似,就是求一个递推式然后把和预处理出来,然后O(1)查询。

一维的递推式是:s[i]=s[i-1]+a[i];

二维的由画图可知:s[i][j]=a[i][j]+s[i-1][j]+s[i][j-1]-s[i-1][j-1];

class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
n=matrix.size();
m=n>?matrix[].size():;
s=vector<vector<int>>(n+,vector<int>(m+,));
for(int i=;i<=n;i++){
for(int j=;j<=m;j++){
s[i][j]=matrix[i-][j-]+s[i-][j]+s[i][j-]-s[i-][j-];
}
}
} int sumRegion(int row1, int col1, int row2, int col2) {
return s[row2+][col2+]-s[row2+][col1]-s[row1][col2+]+s[row1][col1];
}
private:
int n,m;
vector<vector<int> >s;
}; // Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);

最新文章

  1. 理解RESTful架构
  2. 【新手出发】从搭虚拟机开始,一步一步在CentOS上跑起来.Net Core程序
  3. advstringgrid笔记
  4. ie浏览器,背景色兼容解决方法
  5. Spring MVC实例(增删改查)
  6. IOS上传图片
  7. 关于freemarker标签+Spring3.0 V层学习
  8. The 2013 ACM-ICPC Asia Changsha Regional Contest - A
  9. VIP网络水军账号
  10. 转。webapp开发小tips
  11. 关于 WP上应用调试时报错“指定的通信资源(端口)”已由另一个应用程序使用 问题
  12. 使用python进行加密解密AES算法
  13. 5分钟教你玩转 sklearn 机器学习(上)
  14. 客户端热更新框架之UI热更框架设计(上)
  15. Keepalived 的使用
  16. BeanFactory和FactoryBean的区别
  17. Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十):服务熔断(Hystrix、Turbine)
  18. java_二进制的前导的零
  19. CocosCreator内置函数实现物体拖动
  20. android 开发小工具收集

热门文章

  1. .net发布网站步骤
  2. Spring学习十四----------Spring AOP实例
  3. 【翻译自mos文章】执行utlpwdmg.sql之后报ORA-28003, ORA-20001, ORA-20002, ORA-20003, ORA-20004 错误
  4. unslider点导航不显示错误
  5. 关于HDFS NFS3的配置
  6. Python 时间格式化(转)
  7. Android OkHttp的Cookie自己主动化管理
  8. DataGrid绑定Dictionary问题
  9. iOS-代理托付的使用
  10. 【BZOJ2476】战场的数目 矩阵乘法