303+304. Range Sum Query && Range Sum Query 2D
2016-01-31 21:16
387 查看
题目:
Given an integer array nums,
find the sum of the elements between indices i and j (i ≤ j),
inclusive.
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).
思路:
一个非常简单的dp,即dp[i]表示数组从第1个到第i个的和。
还是一个非常简单的dp,即dp[i][j]表示以(i,j)为右下标的长方体内所有数字的和,然而这道题因为null的情况好几次都没有通过!
程序:
Given an integer array nums,
find the sum of the elements between indices i and j (i ≤ j),
inclusive.
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).
思路:
一个非常简单的dp,即dp[i]表示数组从第1个到第i个的和。
还是一个非常简单的dp,即dp[i][j]表示以(i,j)为右下标的长方体内所有数字的和,然而这道题因为null的情况好几次都没有通过!
程序:
public class NumArray { private int[] dp; public NumArray(int[] nums) { int len = nums.length; dp = new int[len+1]; for(int i = 0; i < len; i++) dp[i+1] = dp[i] + nums[i]; } public int sumRange(int i, int j) { return dp[j+1] - dp[i]; } }
public class NumMatrix { private int[][] dp; public NumMatrix(int[][] matrix) { if(matrix == null || matrix.length == 0) return; int row = matrix.length; int col = matrix[0].length; dp = new int[row+1][col+1]; for(int i = 0; i < row; i++) for(int j = 0; j < col; j++) { dp[i+1][j+1] = dp[i+1][j] + dp[i][j+1] - dp[i][j] + matrix[i][j]; } } public int sumRegion(int row1, int col1, int row2, int col2) { return dp[row2+1][col2+1] + dp[row1][col1] - dp[row2+1][col1] - dp[row1][col2+1]; } }
相关文章推荐
- UESTC 766 乐乐和球球 博弈&&暴力(也可以不用暴力法)
- curl continue
- 2.4.6 continue语句
- 细说Java GUI:AWT,SWT,Swing
- php中的全局变量$_REQUEST
- PyQuery基本操作介绍
- 和为0的4个值(4 Values Whose sum is Zero UVa 1152)
- NGUI ScrollView 最彻底优化方案 加载大量(百万级)Item不卡的()
- Bluez调试工具hcitool与gattool的使用实例
- iOS使用XZMRefresh实现UITableView或UICollectionView横向刷新
- B. Guess the Permutation
- UINavigationController练习
- 修改Request 中的数据
- RabbitMQ学习笔记
- Intergraph CADWorx (Plant, P&ID, Equipment, IP, SpecEditor) 2016 v16.0-ISO 1DVD
- java.sql.SQLException: General error, message from server: "Field 'ID' doesn't have a default value
- java.net.SocketException: Can't assign requested address
- busybox filesystem matrix-gui-2.0 undefined function json_encode()
- UItextView回收键盘的几种方式
- LeetCode Unique Binary Search Trees