Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive
2015-11-26 22:11
615 查看
Range Sum Query - Immutable
Total Accepted: 696 Total Submissions: 2406 Difficulty: EasyGiven 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.
public class NumArray { int[] sums; public NumArray(int[] nums) { sums = new int[nums.length]; System.arraycopy(nums, 0, sums, 0, nums.length); for(int i=1; i<sums.length; i++) { sums[i] += sums[i-1]; } } public int sumRange(int i, int j) { if(i>j || i<0 || j<0 || j>=sums.length) return 0; return i==0 ? sums[j] : (sums[j] - sums[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);
相关文章推荐
- 为lua table写保护变成只读
- HDU 1045 Fire Net(二分匹配)
- 拦截器记录
- try catch finally中return的 执行顺序问题
- java中Clendar类详解
- Android官方文档翻译 五 1.3Building a Simple User Interface
- 属性
- DELPHI 任务栏无EXE显示
- 151126
- 经期饮食
- [转载]从 SVM 到多核学习 MKL
- JAVA线程:
- Android开发中Android数据的四种存储方式
- IO异常捕获
- java.lang.Math
- Delphi 全面控制Windows任务栏
- Set&Multiset
- 替换存储表决磁盘的ASM
- DFS求连通块(UVa 572)
- 中兴面试 铩羽而归