当前位置: 首页 > news >正文

LeetCode -- 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).


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
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.




给定一个矩阵,传入(x1,y1) (x2,y2),返回两坐标构成的矩形中包含的数字之和。


思路:
在初始化矩阵时,缓存每个坐标到原点构成的面积(数字之和)。这样多次调用对性能的影响是幂等的。
面积计算时,找出坐标面积之间的关系进行计算即可:设左上坐标为 p0(0,0) ,坐标1 p1(x1,y1),坐标2 p2(x2, y2),并假设p2在p1的右下方(横纵坐标大于等于)。
S = S[x2,y2](总面积) - S[x1-1,y2](x1左侧面积) - S[x2, y1-1](y1上面面积) + S(x1-1,y1-1)(多减去的部分)




实现代码:


public class NumMatrix {
        private int[,] _matrix;
        private int[,] _sum;
        public NumMatrix(int[,] matrix) {
            _matrix = matrix;
    		CreateCache();
        }
    
        public int SumRegion(int row1, int col1, int row2, int col2) {
    		// get the all
    		var areaTotal = _sum[row2, col2]; 
    		
    		// remove the left side sum
    		var areaLeft = col1 > 0 ? _sum[row2, col1-1] : 0;
    		// remove the top side sum
    		var areaTop = row1 > 0 ? _sum[row1-1, col2] : 0;
    		
    		var result = areaTotal - areaLeft - areaTop;
    		// check if there is overlay between top area and left area
    		if(row1 > 0 && col1 > 0){
    			var common = _sum[row1-1,col1-1];
    			result += common;
    		}
    		return result;
        }
    	
    	private void CreateCache(){
    		var rows = _matrix.GetLength(0);
    		var columns = _matrix.GetLength(1);
    		if(rows == 0 && columns == 0){
    			return ;
    		}
    		
    		
    		_sum = new int[rows,columns];
    		
    		// init the first row and column value
    		_sum[0,0] = _matrix[0,0];
    		for (var i = 1;i < rows;i ++){
    			_sum[i,0] = _matrix[i,0] + _sum[i-1,0];
    		}
    		for (var j = 1;j < columns; j++){
    			_sum[0,j] = _matrix[0,j] + _sum[0, j-1];
    		}
    		
    		// from top to bottom , left to right
    		// cache the sum value of each rect
    		for (var i = 1;i < rows; i++){
    			for (var j = 1;j < columns; j++){
    				_sum[i,j] = _matrix[i,j]+ _sum[i,j-1] + _sum[i-1, j] - _sum[i-1,j-1];
    			}
    		}
    		
    	//	Console.WriteLine(_sum);
    	}
}




// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.SumRegion(0, 1, 2, 3);
// numMatrix.SumRegion(1, 2, 3, 4);


相关文章:

  • 从Oracle到DB2,问题集(一)
  • LeetCode -- Dungeon Game
  • 从Oracle到DB2,问题集(二)
  • LeetCode -- Contains Duplicate II
  • Sql union的反义词Minus
  • LeetCode -- Path Sum III
  • LeetCode -- Minimum Number of Arrows to Burst Balloons
  • 反醒反醒
  • LeetCode -- Arranging Coins
  • Bing在中国不会成功
  • LeetCode -- First Unique Character in a String
  • 搜狗输入法,无心插柳柳成荫
  • LeetCode -- Wildcard Matching
  • 弥平“第三道鸿沟”:3G运营商必须承担的社会责任
  • 使用面向对象重构之-从过程式设计到面向对象
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • Android框架之Volley
  • eclipse(luna)创建web工程
  • ES6之路之模块详解
  • QQ浏览器x5内核的兼容性问题
  • XML已死 ?
  • 利用阿里云 OSS 搭建私有 Docker 仓库
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 我的zsh配置, 2019最新方案
  • 线上 python http server profile 实践
  • 找一份好的前端工作,起点很重要
  • ionic异常记录
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • 通过调用文摘列表API获取文摘
  • ​一些不规范的GTID使用场景
  • # 数论-逆元
  • #{} 和 ${}区别
  • #13 yum、编译安装与sed命令的使用
  • (01)ORB-SLAM2源码无死角解析-(56) 闭环线程→计算Sim3:理论推导(1)求解s,t
  • (6)设计一个TimeMap
  • (C++17) std算法之执行策略 execution
  • (Oracle)SQL优化技巧(一):分页查询
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (论文阅读40-45)图像描述1
  • (幽默漫画)有个程序员老公,是怎样的体验?
  • (转)jQuery 基础
  • (转)甲方乙方——赵民谈找工作
  • ***php进行支付宝开发中return_url和notify_url的区别分析
  • .halo勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .net 打包工具_pyinstaller打包的exe太大?你需要站在巨人的肩膀上-VC++才是王道
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .NET高级面试指南专题十一【 设计模式介绍,为什么要用设计模式】
  • .NET学习全景图
  • .Net中wcf服务生成及调用
  • @Autowired和@Resource装配
  • [ C++ ] STL priority_queue(优先级队列)使用及其底层模拟实现,容器适配器,deque(双端队列)原理了解
  • [【JSON2WEB】 13 基于REST2SQL 和 Amis 的 SQL 查询分析器
  • [android学习笔记]学习jni编程
  • [c#基础]DataTable的Select方法