Range Sum Query 2D - Immutable
2016-01-09 15:05
1026 查看
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)
![](http://img.blog.csdn.net/20160109135155995)
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
思路:
![](http://img.blog.csdn.net/20160109164052733)
Example:
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.
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:
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.
public class NumMatrix { int[][] matrix ; int[][] area; public NumMatrix(int[][] matrix) { if(matrix!=null && matrix.length!=0) { int m=matrix.length; int n=matrix[0].length; this.matrix=matrix; this.area=new int[m] ; area[0][0]=matrix[0][0]; for(int i=1;i<n;i++) { area[0][i]=area[0][i-1]+matrix[0][i]; } for(int j=1;j<m;j++) { area[j][0]=area[j-1][0]+matrix[j][0]; } for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { area[i][j]=area[i-1][j]+area[i][j-1]-area[i-1][j-1]+matrix[i][j]; } } } } public int sumRegion(int row1, int col1, int row2, int col2) { int res=0; int m = matrix.length; if(m==0) return res; int n = matrix[0].length; if(n==0) return res; if(row1 <= row2 && col1 <= col2) { if(row1>=1 && col1>=1 ) res = area[row2][col2]-(area[row1-1][col2] + area[row2][col1-1]-area[row1-1][col1-1]); else if(row1==0 && col1==0) res=area[row2][col2]; else if(row1==0) res = area[row2][col2] - area[row2][col1-1]; else res =area[row2][col2]-area[row1-1][col2]; } return res; } } // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix = new NumMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.sumRegion(1, 2, 3, 4);
相关文章推荐
- NSDate,NSNumber,NSValue
- IOS UIControl、UIButton
- UIView的基本控件
- 建造者模式(Builder和Director)
- 三种UITableViewCell刷新的方法
- iOS开发 UI UIScrollView和UIPageController
- 显示图像数据的高级接口 UIImage
- UI自动化测试-UiAutomator
- Easyui数据表格-地区列表及工具栏增删改
- MySQL性能剖析工具(pt-query-digest)
- iOS本地通知 UILocalNotification 笔记
- LeetCode() Range Sum Query-mutable
- 146_尺取法 subsequence (POJ No 3061)
- A beginner's guide to writing a custom stream buffer (std::streambuf)
- UITableViewCell左侧会有默认15像素的空白
- C# 集合类 :(Array、 Arraylist、List、Hashtable、Dictionary、Stack、Queue)
- Variable ‘time_zone’ can’t be set to the value of ‘NULL’解决方法
- django例子,question_text为中文时候报错
- UIImage与UIColor互转
- 不可变字典 赋值 求字典里有多少对 获取字典里所有value值 获取所有考值