304. Range Sum Query 2D
来源:互联网 发布:淘宝运营岗位要求 编辑:程序博客网 时间:2024/06/05 06:05
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).Range Sum Query 2DThe above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
- 这道题目本身比较简单,不过稍微略显繁琐。对于其中的部分细节问题要特殊处理。
class NumMatrix {public: vector<vector<int>> myMatrix; NumMatrix(vector<vector<int>> matrix) { int n = matrix.size(); if(n <= 0){ return; } int m = matrix[0].size(); if(m <= 0){ return ; } for(int i = 0; i < n;i++){ myMatrix.push_back(matrix[i]); } myMatrix[0][0] = matrix[0][0]; //intial the first colum for(int i = 1;i < n; ++i){ myMatrix[i][0] = matrix[i][0] + myMatrix[i-1][0]; } //initial the first row for(int i = 1;i < m; ++i){ myMatrix[0][i] = matrix[0][i] + myMatrix[0][i-1]; } //dp & initial the sum matrix for(int i = 1;i < n; ++i){ for(int j = 1;j < m; ++j){ myMatrix[i][j] = matrix[i][j] + myMatrix[i-1][j] + myMatrix[i][j-1] - myMatrix[i-1][j-1]; cout<<myMatrix[i][j]<<","; } cout<<endl; } return; } int sumRegion(int row1, int col1, int row2, int col2) { if(row1 < 0 || row2 < 0 || col1 < 0 || col2 < 0){ return 0; } if(myMatrix.size() <= 0 || myMatrix[0].size() <= 0){ return 0; } int result = myMatrix[row2][col2]; if(row1 > 0){ result -= myMatrix[row1-1][col2]; } if(col1 > 0){ result -= myMatrix[row2][col1-1]; } if(row1 > 0 && col1 > 0){ result += myMatrix[row1-1][col1-1]; } return result; }};/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */
阅读全文
0 0
- 303+304. Range Sum Query && Range Sum Query 2D
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable**
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D
- 304. Range Sum Query 2D
- 304. Range Sum Query 2D
- 304. Range Sum Query 2D
- 304. Range Sum Query 2D
- leetcode 304. Range Sum Query 2D
- day02-还是tkinter
- 《java编程思想》第5章
- 总结-2017/9/21
- HDU
- 2039-数据结构上机实验之二分查找
- 304. Range Sum Query 2D
- H3C无线控制器做用户隔离和DHCP Relay的注意事项
- MQL5语法基础(三)
- Google账户设置
- Hibernate
- lua中的元方法__index __newIndex
- Count Color(线段树+染色问题)
- hdu 2091(空心三角形)
- blog