303. Range Sum Query - Immutable
2016-07-09 22:57
337 查看
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
维护一个数组sum记录到当前位置的和,所求的(i,j)的和就是 sum[j]-sum[i-1]
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.
维护一个数组sum记录到当前位置的和,所求的(i,j)的和就是 sum[j]-sum[i-1]
long sum = 0; long[] sums; public NumArray(int[] nums) { int len = nums.length; sums = new long[len]; for (int i = 0; i < len; i++) { sum += nums[i]; sums[i] = sum; } } public int sumRange(int i, int j) { return (int)(sums[j]-(i>=1?sums[i-1]:0)); }
相关文章推荐
- Java中toString(),(String),valueOf()的区别与联系
- UIPickerView简单实用
- 300. Longest Increasing Subsequence
- 生成器模式(Builder)
- 关于UITableView中Cell的保持/保存 选中状态的简单方法
- hibernate中Query的list和iterator区别(续)
- UINavigationController 的一些坑
- POJ1904 King's Quest(完备匹配可行边:强连通分量)
- [置顶] The requested resource (/) is not available
- UINavigationController改变背景颜色
- LeetCode - 112. Path Sum
- Label设置行间距
- 火眼金睛:continue&break
- UESTC 842 天下归晋(树状数组)
- UESTC 841 休生伤杜景死惊开(树状数组)
- UESTC 838 母仪天下(树状数组)
- Parquet与ORC:高性能列式存储格式
- Android UI布局优化
- easyui datagrid 小结
- POJ1417 True Liars (并查集+背包)