Leetcode no. 304
来源:互联网 发布:巨杉数据库 王涛 编辑:程序博客网 时间:2024/05/18 11:48
304. Range Sum Query 2D - Immutable
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.
public class NumMatrix { private int[][] dp; public NumMatrix(int[][] matrix) { if (matrix.length==0 || matrix[0].length==0) return; int row= matrix.length; int col= matrix[0].length; dp= new int[row+1][col+1]; for (int i = 1; i < row+1; i++) { for (int j = 1; j < col+1; j++) { dp[i][j]=dp[i-1][j]+ dp[i][j-1] - dp[i-1][j-1] + matrix[i-1][j-1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { return dp[row2+1][col2+1]- dp[row1][col2+1] - dp[row2+1][col1] + dp[row1][col1]; }}// 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);
0 0
- Leetcode no. 304
- LeetCode No.11 ~No.12
- Leetcode NO.78 Subsets
- Leetcode NO.77 Combinations
- Leetcode NO.46 Permutations
- 【leetcode】No. 235 LCABST
- LeetCode no. 35
- Leetcode no. 37
- Leetcode no. 279
- Leetcode no. 335
- Leetcode no. 283
- Leetcode no. 181 (sql)
- Leetcode no. 40
- Leetcode no. 238
- Leetcode no. 26
- Leetcode no. 80
- Leetcode no. 228
- Leetcode no. 313
- 文学研究助手
- MySQL中concat函数
- 嵌入式软件段错误调试方法--core文件的使用(海思3520d电路板为例,附执行脚本)
- Android BaseAdapter
- [计服15] 5.18实验
- Leetcode no. 304
- <c:forEach>详解
- DataGridView窗体之间的传递
- [2014-9-9]反射
- [2014-9-10]异步编程
- [2014-9-11]异步编程继续
- HDU 3836 Equivalent Sets(强连通分量)
- [2014-9-12]多线程
- [2014-9-13]委托多线程