[leetcode] 304. Range Sum Query 2D - Immutable 解题报告
2015-12-22 06:09
609 查看
题目链接:https://leetcode.com/problems/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:
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.
思路:和Range Sum Query - 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) -> 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.
思路:和Range Sum Query - Immutable一样,那一题是一维,这题是二维,但是方法都一样,都是存储一行到每一个位置之前数的和是多少。最后要求区间的时候就把前面的区间和去掉。
代码如下:
class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) { hash.resize(matrix.size()); for(int i = 0; i< matrix.size(); i++) { hash[i].resize(matrix[i].size()+1); hash[i][0] = 0; for(int j = 0; j < matrix[i].size(); j++) hash[i][j+1] = hash[i][j] + matrix[i][j]; } } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for(int i = row1; i <= row2; i++) sum += (hash[i][col2+1] - hash[i][col1]); return sum; } private: vector<vector<int>> hash; }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.sumRegion(1, 2, 3, 4);
相关文章推荐
- [leetcode] 303. Range Sum Query - Immutable 解题报告
- Divide and Conquer:Cable Master(POJ 1064)
- Team Queue UVA540
- java中ProcessBuilder
- js实现C#的StringBuilder效果完整实例
- Divide and Conquer:Monthly Expense(POJ 3273)
- Request的getParameter和getAttribute方法的区别
- request.getScheme() 使用方法
- JavaSE的UI界面编程
- CALayer 花瓣飘落 转场动画-CATransation 动画组 UIView动画封装
- iOS - UIImageView
- iOS- UIProgressView
- UI相关基础知识
- BlockQueue使用之简单应用
- UIScrollView,UITableView的简单使用
- Riemann积分和Lebesgue积分角度下一积分不等式的等号成立充要条件的研究
- MySQL提示:The server quit without updating PID file问题的解决办法
- 设置UILabel的行间距
- 关于很简单的设计模式,ui-dao-database,以及JavaBean和util工具类
- 笔记-引导页GuideActivity