https://leetcode.cn/problems/range-sum-query-immutable/
知识点:前缀和,不过是一维的。
我的代码
class NumArray {
// sum[i]表示 0到i(包含)的和
private int[] sums;
public NumArray(int[] nums) {
int n = nums.length;
sums = new int[n];
int sum = 0;
for(int i=0;i<n;i++){
sum += nums[i];
sums[i] = sum;
}
}
public int sumRange(int left, int right) {
if(left==0){
return sums[right];
}else{
return sums[right] - sums[left-1];
}
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/