LeetCode-Range Sum Query- Immutable

LiBlog發表於2016-08-15

Given an integer array nums, find the sum of the elements between indices i and j (ij), 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.

Solution:

 1 public class NumArray {
 2     int[] sums;
 3     public NumArray(int[] nums) {
 4         sums = new int[nums.length];
 5         int sum = 0;
 6         for (int i=0;i<nums.length;i++){
 7             sum += nums[i];
 8             sums[i] = sum;
 9         }
10     }
11 
12     public int sumRange(int i, int j) {
13         int sum1 = (i==0) ? 0 : sums[i-1];
14         int sum2 = sums[j];
15         return sum2 - sum1;
16     }
17 }
18 
19 
20 // Your NumArray object will be instantiated and called as such:
21 // NumArray numArray = new NumArray(nums);
22 // numArray.sumRange(0, 1);
23 // numArray.sumRange(1, 2);

 

相關文章