Leetcode no. 303

来源:互联网 发布:淘宝店铺改域名 编辑:程序博客网 时间:2024/06/05 11:36

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

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

public class NumArray {    private int[] res;    public NumArray(int[] nums) {        for (int i=1; i<nums.length; i++){            nums[i]+=nums[i-1];        }        this.res= nums;    }    public int sumRange(int i, int j) {        if (i==0) return res[j];        return res[j]-res[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
原创粉丝点击