leetcode(58)-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:
You may assume that the array does not change.
There are many calls to sumRange function.

思路:

  • 题意:要求给定坐标区间的数组的和,题目要求是大量的使用。所以须要构造缓存,构造缓存的方法就是记录,把num[i~j]的和,变为num[0~j]-num[0~i],这样就是缓存了一个长度为length的和

代码:

public class NumArray {
   private int[] num = null;
    public NumArray(int[] nums) {
        int all = 0;
        num = new int[nums.length];
        for(int i = 0; i < nums.length;i++){
            all = all+nums[i];
            num[i] = all;
        }
    }

    public int sumRange(int i, int j) {
       return i == 0 ? num[j]:num[j]-num[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);

转载于:https://www.cnblogs.com/llguanli/p/7241171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值