[leetcode] 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) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.

分析:利用一个数组sum缓存累积的和,建立数组sum的时间复杂度O(N),之后每次sumRange查询时间复杂度都为O(1).

Java代码:

public class NumArray{
    int[] sum;
    public NumArray(int[] nums) {
        sum = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            sum[i+1] = sum[i] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        return sum[j+1] - sum[i];
    }
}

 

posted @ 2015-11-11 15:13  lasclocker  阅读(230)  评论(0编辑  收藏  举报