Range Sum Query 2D - Immutable
2015-11-15 18:03
197 查看
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:
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.
class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) { int sum = 0; for (int i = 0; i < matrix.size(); i++) { vector<int> row; sum = 0; for (int j = 0; j < matrix[i].size(); j++) { sum += matrix[i][j]; if (i == 0) { row.push_back(sum); } else { row.push_back(sum + this->matrix[i - 1][j]); } } this->matrix.push_back(row); } } int sumRegion(int row1, int col1, int row2, int col2) { int res = 0; if (row1 != 0 && col1 != 0) { res = matrix[row2][col2] - matrix[row1 - 1][col2] - matrix[row2][col1 - 1] + matrix[row1 - 1][col1 - 1]; } else if (row1 == 0 && col1 != 0) { res = matrix[row2][col2] - matrix[row2][col1 - 1]; } else if (row1 != 0 && col1 == 0) { res = matrix[row2][col2] - matrix[row1 - 1][col2]; } else { res = matrix[row2][col2]; } return res; } private: vector<vector<int>> matrix; };
相关文章推荐
- UIAlertView用法
- 使用UITextFieldDelegate来隐藏键盘
- UIButton使用方法汇总
- UITextField用法总汇
- 探究toString()和valueOf()
- IOS UIAlertView
- 05 ueditor上传图片配置
- 【LigerUI实战】Grid弹出编辑popup
- [转]UIModalPresentationStyle和UIModalTransitionStyle
- FetchRequestController
- Android Stduio的使用(七)--Structure窗口
- IOS UISlider
- GPUImage API文档之GPUImageInput协议
- UIButton
- 开源,部落冲突辅助,C#4.6,win10,bluestacks最新。
- iOS引用当前显示的UIAlertView
- <%=request.getContextPath()%>的作用
- iOS之UI初级---UIWindow的基本内容
- UIView
- UI框架