@Yano 2016-03-21T12:31:10.000000Z 字数 781 阅读 2602

# LeetCode 303 Range Sum Query - Immutable

LeetCode

# 题目描述

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:

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

# 代码

public class NumArray {    public long[] sum;    public NumArray(int[] nums) {        sum = new long[nums.length + 1];        for (int i = 0; i < nums.length; i++) {            sum[i + 1] += nums[i] + sum[i];        }    }    public int sumRange(int i, int j) {        if (i > j || i < 0 || j >= sum.length - 1) {            return Integer.MIN_VALUE;        }        return (int) (sum[j + 1] - sum[i]);    }}// Your NumArray object will be instantiated and called as such:// NumArray numArray = new NumArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);

• 私有
• 公开
• 删除