您的位置:首页 > 产品设计 > UI/UE

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:

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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: