[LeetCode] Range Sum Query - Immutable
2015-11-10 15:09
351 查看
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
解题思路
考虑到要多次调用sumRange()函数,因此需要把结果先存起来,调用时就可以直接返回了。最开始考虑的是用
dp[i][j]来直接存储
i到
j之间元素的和,但是内存超出限制。于是考虑用
dp[i]来存储
0到
i之间元素的和,
0到
j的和减去
0到
i-1的和即为所求。
实现代码
// Runtime: 3 ms public class NumArray { private int[] dp; public NumArray(int[] nums) { dp = new int[nums.length]; int sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; dp[i] = sum; } } public int sumRange(int i, int j) { return i == 0 ? dp[j] : dp[j] - dp[i - 1]; } } // Your NumArray object will be instantiated and called as such: // NumArray numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2);
相关文章推荐
- 项目嵌入环信UI
- iOS开发——UI组件整理
- 自定义UITableViewCell(registerNib: 与 registerClass: 的使用)
- Bluemix 动手系列 (一) 部署你的第一个云应用
- Learning Bluemix 微信公众号
- Confluence 用户指南
- [DruidAbstractDataSource] maxIdle is deprecated
- easyui的树表格使用总结
- SEC phase
- (转)ZwQuerySystemInformation枚举内核模块及简单应用
- 快速排序 温习 QuickSort
- build-tools
- iOS小技巧-UITableView禁止上下滑动超出顶部或者底部的内容
- java.sql.SQLException: No suitable driver found for
- UILable
- [LeetCode] Range Sum Query - Immutable
- break;与continue;的区别
- Android快速SDK(2)View库QuickView
- 视图view,序列sequence
- hdu2767Proving Equivalences【STL版SCCTarjan+缩点】(有注释)