前缀和法
/*
* @lc app=leetcode.cn id=303 lang=java
*
* [303] 区域和检索 - 数组不可变
*/
// @lc code=start
class NumArray {
public int[] nums;
// 普通方法
// public NumArray(int[] nums) {
// this.nums = nums;
// }
// public int sumRange(int left, int right) {
// int sum = 0;
// while(left <= right){
// sum += this.nums[left++];
// }
// return sum;
// }
// 前缀和法
public NumArray(int[] nums) {
int[] arr = new int[nums.length + 1];
for(int i = 0; i < nums.length; i++){
arr[i + 1] = arr[i] + nums[i];
}
this.nums = arr;
}
public int sumRange(int left, int right) {
return nums[right + 1] - nums[left];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
// @lc code=end