Leetcode 304. Range Sum Query 2D
来源:互联网 发布:fifa online3数据库 编辑:程序博客网 时间:2024/06/07 23:04
问题描述
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) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12
Note:
- You may assume that the matrix does not change.
- There are many calls to sumRegion function.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
定义数组sum[i][j]表示从[0,0]到[i,j]的矩形的面积,利用容斥定理A||B=A+B-A&&B
代码如下:
public class NumMatrix { int[][]sum; int n; int m; public NumMatrix(int[][] matrix) { n=matrix.length; if(n>0) m=matrix[0].length; if(n>0&&this.m>0){ sum=new int[n][m]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ sum[i][j]=matrix[i][j]; if(i>=1) sum[i][j]+=sum[i-1][j]; if(j>=1) sum[i][j]+=sum[i][j-1]; if(i>=1&&j>=1) sum[i][j]-=sum[i-1][j-1]; } } } } public int sumRegion(int row1, int col1, int row2, int col2) { if(row1<0||row2>=n||col1<0||col2>m) return -1; if(n==0) return 0; int ans=sum[row2][col2]; if(row1>=1) ans-=sum[row1-1][col2]; if(col1>=1) ans-=sum[row2][col1-1]; if(row1>=1&&col1>=1) ans+=sum[row1-1][col1-1]; return ans; }}
阅读全文
0 0
- leetcode 304. Range Sum Query 2D
- leetcode 304. Range Sum Query 2D
- [LeetCode]304. Range Sum Query 2D
- [leetcode]304. Range Sum Query 2D
- Leetcode 304. Range Sum Query 2D
- [Leetcode] 304. Range Sum Query 2D
- leetcode 304.Range Sum Query 2D
- leetcode 304. Range Sum Query 2D
- leetcode 304. Range Sum Query 2D
- [Leetcode]Range Sum Query 2D - Immutable
- Leetcode Range Sum Query 2D - Immutable
- LeetCode Range Sum Query 2D - Immutable
- [Leetcode]Range Sum Query 2D - Immutable
- Leetcode Range Sum Query 2D - Immutable
- Leetcode: Range Sum Query 2D - Immutable
- Leetcode: Range Sum Query 2D - Immutable
- leetcode:Range Sum Query 2D - Immutable
- LeetCode|Range Sum Query 2D - Immutable
- Android并发编程之白话文详解Future,FutureTask和Callable
- 如何让ubuntu系统中的g++支持c++11标准
- Java打包与导包
- 数据压缩实验八:H264编码
- iOS App store 应用审核由于 IPv6 网络问题被拒的一点分析
- Leetcode 304. Range Sum Query 2D
- MySQL操作数据库命令汇总之windows 命令行使用
- Super Jumping! Jumping! Jumping! HDU
- [前端]LocalResizeImg的使用技巧、与Struts2的结合以及一些坑点
- Android广播系列
- 解决在MySQL中插入中文出现"Incorrect string value"的问题
- Python爬虫学习之爬美女图片
- HDU 6030 Happy Necklace (递推+矩阵快速幂)
- 贝塞尔曲线扫盲