LeetCode 303 : Range Sum Query - Immutable (Java)

本文介绍了一种区间和查询的高效算法。通过预处理数组元素的累积和,可以在常数时间内计算任意区间的元素总和,避免了重复计算,显著提高了查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:此题和以往的题目所给的形式不同。由于sumRange函数会被调用多次,所以如果具体的求和在sumRange中实现的话很不划算,因为多了很多重复计算,比如求(0,2)和(0, 3)范围内的和,其实后者仅需要在前者基础上加上第3个数而已,并不需要从头重新计算一遍。因此,一个较好的思路是在构造函数中完成从0到所有位置之间的元素的和并进行存储,这样到了sumRange函数中只需要取出即可,顶多再做一个减法,有效地避免了重复计算。

public class NumArray {
    public int[] sums;

    public NumArray(int[] nums) {
        if (nums == null) {
            sums = null;
        } else if (nums.length == 0) {
            sums = new int[0];
        } else {
            this.sums = new int[nums.length];
            sums[0] = nums[0];
            for (int i = 1; i < nums.length; i++) {
                sums[i] = sums[i - 1] + nums[i];
            }
        }
    }

    public int sumRange(int i, int j) {
        if (sums == null) {
            return 0;
        }
        if (i >= sums.length || j >= sums.length || i > j) {
            return 0;
        } else if (i == 0) {
            return sums[j];
        } else {
            return sums[j] - sums[i - 1];
        }
    }
}


// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值