一、题目
Given an integer array nums, handle multiple queries of the following type:
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.
int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
二、 思路
前缀和主要适⽤的场景是原始数组不会被修 改的情况下,频繁查询某个区间的累加和。其实就是再建个数组,存前n项和,然后到时候求区间和的时候,直接数组内对应两个下标一减就ok了。
二、自己写的
1.代码
第一次写
class NumArray {
private int[] num;
public NumArray(int[] nums) {
//定义一个数组num,来存从NumArray中得到的数组,NumArray中形参的名字叫nums,也就是说,系统是通过nums传进来的数组,我要把它赋给num来自己用,所以是num=nums
num = nums;
//假如把自己定义的数组叫nums
//因为整个程序传入的参数是名字为nums的数组,而NumArray的形参也是名字为nums的数组,所以加个this表示是这个形参
//相当于,把整个程序传入的nums,赋给NumArray中的nums
// this.nums = nums;
}
public int sumRange(int left, int right) {
int res = 0;
for (int i = left; i <= right; i++) {
res += num[i];
}
return res;
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
正确,但是这是最笨的方法
第二次写
class NumArray {
private int[] num;
public NumArray(int[] nums) {
//数组求length的话是nums.length,不是nums.length()
num = new int[nums.length];
num[0] = nums[0];
for (int i = 1; i < num.length; i++)
num[i] = num[i - 1] + nums[i];
}
public int sumRange(int left, int right) {
if (left == 0)
return num[right];
return num[right] - num[left - 1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
//正确,得画画图,看看这个数组的表示问题,很容易越界。
三、标准答案
class NumArray {
private int[] preSum;
public NumArray(int[] nums) {
//preSum[0]=0 便于计算累加和
preSum = new int[nums.length + 1];
preSum[0] = 0;
//这样计算累加和的话,直接从1开始就行了,不然从0开始要很麻烦,还有可能有负数
for (int i = 1; i < preSum.length; i++)
preSum[i] = preSum[i - 1] + nums[i - 1];
}
public int sumRange(int left, int right) {
return preSum[right + 1] - preSum[left];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(left,right);
*/
总结
其实就是直接在读取数组的时候,顺便一个for循环求出来前n个数字的和,放到一个新数组里,用的时候直接两个一减就完事儿了。这个题无所谓怎么定义,都能绕过来,但是下一个题最好是按这种方式定义preSum,不然容易晕。