Range Sum Query - Immutable
来源:互联网 发布:为什么胡歌没女友 知乎 编辑:程序博客网 时间:2024/06/04 23:28
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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
这道题要求区间内的和。可以想到,用一个数组保存前n项的和,然后用大的区间减去小的区间就得到中间的那个区间的和。
注意下这个sum数组的长度为n+1, sum[0] = 0,表示当前下标前的和为多少。对应计算差值的时候, 举个例子就能知道下标该如何写了。
例子:
nums = [1, 2, 3, 4]
sums= [0, 1, 3, 6, 10]
例如计算:sumRange(0, 2): sums[2+1] - sum[0] = 6
代码:
int[] nums; int [] sums; public NumArray(int[] nums) { this.nums = nums; this.sums = new int[nums.length+1]; if(nums.length>0){ sums[0] = nums[0]; for(int i=0;i<nums.length;i++){ sums[i+1] = sums[i] + nums[i]; } } } private int sumRange(int i, int j) { return sums[j+1] - sums[i]; }
0 0
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Range Sum Query - Immutable
- Error:(16, 0) Gradle DSL method not found: 'Android()'
- Android创建底部菜单栏
- Android开发第1天
- Leetcode 113. Path Sum II (Medium) (cpp)
- 09-CoreData iOS10.0变化
- Range Sum Query - Immutable
- 10-NSPersistentContainer介绍
- 11-使用NSPersistentContainer搭建CoreData Stack
- 12-CoreData操作大量数据时的注意细节
- 13-NSPersistentContainer性能比较
- 14-CoreData兼容iOS9和iOS10
- BeautifulSoup的高级应用 之 find findAll
- 搬家了,以后 在 www.JiFei.co 上写文章了。。。
- LeetCode 465. Optimal Account Balancing