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

[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.

解题思路

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