@Yano
2016-03-21T20:31:10.000000Z
字数 781
阅读 2684
LeetCode
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:
题目中描述,函数可能被调用很多次,并且函数是不可变的。那么可以构造一个数组sum,sum[i] 存放数组 nums从 0 到 i 的和,这样能在 O(1) 的复杂度内求出指定范围的和。
public class NumArray {
public long[] sum;
public NumArray(int[] nums) {
sum = new long[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
sum[i + 1] += nums[i] + sum[i];
}
}
public int sumRange(int i, int j) {
if (i > j || i < 0 || j >= sum.length - 1) {
return Integer.MIN_VALUE;
}
return (int) (sum[j + 1] - sum[i]);
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);