leetcode(58)-Range Sum Query - Immutable

来源:互联网 发布:基于云计算的oracle 编辑:程序博客网 时间:2024/06/08 14:30

题目:

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3Note: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);
0 0
原创粉丝点击