LeetCode--No.303--Range Sum Query - Immutable

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:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Subscribe to see which companies asked this question

1. 最开始这个题目下面的代码是这样子的:

public class NumArray {
    int[] prefixSum;
    
    public NumArray(int[] nums) {
    }
    public int sumRange(int i, int j) {
    }
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

最开始的想法有点儿脑残,觉得sumRange不就是相加一下就好了嘛。可是并不明白NumArray存在的意义。
现在看来,NumArray numArray = new NumArray(nums) 这个步骤之后,nums这个参数并不能传递给sumRange这个函数,所以要想办法把参数传递过去。

2. 我写了一个版本是这样子的

public class NumArray {
    int[] a;
    public NumArray(int[] nums) {
        int len = nums.length;
        a = new int[len];
        for(int i = 0; i < len; i++)
            a[i] = nums[i];
    }
    public int sumRange(int i, int j) {
        int res = 0;
        for(int k = i; k <= j; k++)
            res += a[k];
        return res;
    }
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
我想的是,将nums数组赋值给全局变量数组a,那么函数sumRange每次就都可以直接调用a了,这样参数就可以传递好了。但速度太慢了。。。再看下题目,sumRange会调用很多很多次,所以每一次都要遍历数组。所以重新写一下。

3. 重新写了一下是这样子的

public class NumArray {
    int[] prefixSum;
    public NumArray(int[] nums) {
        int len = nums.length;
        prefixSum = new int[len+1];
        prefixSum[0] = 0;
        for(int i = 1; i <= len; i++){
            prefixSum[i] = prefixSum[i-1] + nums[i-1];
        }
    }
    public int sumRange(int i, int j) {
        return (prefixSum[j+1] - prefixSum[i]);
    }
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

这里面的小trick, prefixSum 长度比nums多一。
这样不论i和j取值为几,都可以用一个减法解决。不然i=0的情况,是不需要减去前面数字的情况,还需要再判断,代码会很不清晰,逻辑更复杂,速度也会变慢。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值