[LeetCode]303. Range Sum Query

来源:互联网 发布:怎么开个淘宝网店代理 编辑:程序博客网 时间:2024/06/06 00:19

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.


思路:很简单,用一个同等长度的数组存到i元素的所有和,返回range的时候就用sum[j]-sum[i-1]

public class NumArray {    int[] sum;    public NumArray(int[] nums) {        sum=new int[nums.length];        int s=0;        for(int i=0;i<nums.length;i++){            s+=nums[i];            sum[i]=s;        }    }        public int sumRange(int i, int j) {        if(i>0){            return sum[j]-sum[i-1];        }else{            return sum[j];        }            }}/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */


0 0
原创粉丝点击