leetcode(58)-Range Sum Query - Immutable

时间:2021-10-10 04:44:26

题目:

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);