博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 304. Range Sum Query 2D - Immutable
阅读量:7200 次
发布时间:2019-06-29

本文共 2052 字,大约阅读时间需要 6 分钟。

04. Range Sum Query 2D - Immutable

   
QuestionEditorial Solution
Total Accepted: 12544 Total Submissions: 56503 Difficulty: Medium

 

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) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12

 

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

 

 

 to see which companies asked this question

Hide Tags
 
Show Similar Problems
 
 

Submission Details

12 / 12 test cases passed.
Status: 

Accepted

Runtime: 24 ms

 

 

思路:动态规划

 
1 class NumMatrix { 2 public: 3     NumMatrix(vector
> &matrix) { 4 if(matrix.empty()){ 5 return; 6 } 7 int n = matrix.size(), m = matrix[0].size(); 8 sums = vector
>(n+1, vector
(m+1, 0)); 9 int i,j;10 sums[0][0] = matrix[0][0];11 for(i = 1;i <= n;i++){12 for(j = 1;j <= m;j++){13 sums[i][j] = sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1] + matrix[i -1][j - 1];14 }15 }16 }17 18 int sumRegion(int row1, int col1, int row2, int col2) {19 return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];20 }21 22 private: 23 vector
> sums;24 };25 26 27 // Your NumMatrix object will be instantiated and called as such:28 // NumMatrix numMatrix(matrix);29 // numMatrix.sumRegion(0, 1, 2, 3);30 // numMatrix.sumRegion(1, 2, 3, 4);

 

转载于:https://www.cnblogs.com/njczy2010/p/5489057.html

你可能感兴趣的文章
如今的SEO与以往的SEO有何不同?
查看>>
ASP.NET 5系列教程 (一):领读新特性
查看>>
平台类网站为非星级酒店带来营销新机遇
查看>>
iphone5最新谍讯汇总
查看>>
Json概述以及python对json的相关操作
查看>>
用Saltstack的returners实现批量监控和数据存储
查看>>
四大特色引人注目瑞星ESM SOHO版全力护航小微企业
查看>>
闲聊明星形象对代言产品的影响
查看>>
与大数据打交道的那些人
查看>>
SQL JOIN--Nested Join
查看>>
linu下 php+nginx+mysql安装配置
查看>>
【轻松一刻】那些让我们惊叹不已的唯美GIF动态图片
查看>>
Html.ActionLink
查看>>
Qt事件处理(二)
查看>>
Baruwa 1.1.2 发布,邮件监控系统
查看>>
C# 的关键字系列(4 of n)
查看>>
在获取textbox的时候 如果要转换为int的 可能会出错 如果为空
查看>>
Monkey Studio IDE | The way IDEs should be
查看>>
处理散列冲突的方法
查看>>
「Linux」Linux下根据CET听力文件关键字和lcr时间对mp3进行剪辑分割
查看>>