Range Sum Query 2D
来源:互联网 发布:淘宝店铺保证金在哪交 编辑:程序博客网 时间:2024/05/16 15:17
Range Sum Query 2D - Immutable
题目来源:https://leetcode.com/problemset/algorithms/
题目类型:动态规划
-题目描述-
-解题思路-
-代码实现-
题目描述
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 2D
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
解题思路
题意为计算一个矩阵中指定矩形内的元素的和。即将matrix[i][j](row1<=i<= row2&&col1<=j<= col2)累加就可以得到结果。
代码实现
@requires_authorizationclass NumMatrix {public: NumMatrix(vector<vector<int>> matrix) { for (int i = 0; i < matrix.size(); i++) { vector<int> col; for (int j = 0; j < matrix[i].size(); j++) { col.push_back(matrix[i][j]); } this->matrix.push_back(col); } } int sumRegion(int row1, int col1, int row2, int col2) { if (!(row1 <= row2&&col1 <= col2)) return 0; int sum = 0; for (int i = row1; i <= row2; i++) { for (int j = col1; j <= col2; j++) { sum += matrix[i][j]; } } return sum; } private: vector<vector<int>> matrix;};
阅读全文
0 0
- Range Sum Query 2D
- Range Sum Query 2D
- 303+304. Range Sum Query && Range Sum Query 2D
- Range Sum Query 2D - Immutable
- Range Sum Query 2D - Immutable
- [Leetcode]Range Sum Query 2D - Immutable
- Range Sum Query 2D - Immutable
- Leetcode Range Sum Query 2D - Immutable
- LeetCode Range Sum Query 2D - Immutable
- [LeetCode308]Range Sum Query 2D - Mutable
- [Leetcode]Range Sum Query 2D - Immutable
- Leetcode194: Range Sum Query 2D - Immutable
- Leetcode Range Sum Query 2D - Immutable
- Leetcode: Range Sum Query 2D - Immutable
- Range Sum Query 2D - Immutable
- Leetcode: Range Sum Query 2D - Immutable
- LeetCode304. Range Sum Query 2D - Immutable
- 304. Range Sum Query 2D - Immutable
- 错误:仅当显示请求注释处理时才接受类名称
- seaborn 可视化包
- 全是套路的招聘
- 学习Js(1)-使用Jquery实现滑动切换效果
- 记录一篇IDEA环境搭建JFinal框架的demo
- Range Sum Query 2D
- JSON的简单介绍以及C语言的JSON库使用
- 综合练习之--2、MainActivity | Fragment 显示XLV 和 侧滑 vp效果的代码
- Webpack noParse参数
- Android使用ZXing扫描二维码,并返回二维码结果
- 如何为nginx配置https(免费证书)
- 命名规范
- c:if标签的判断
- android databinding recyclerview多种itembinding