LeetCode 303. Range Sum Query - Immutable

原题链接在这里:https://leetcode.com/problems/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:

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

题解: 

因为这个函数会被多次调用,每次都算一遍会花很多时间, 所以用dp数组来保存过去的值.

dp[i] 表示 nums[0]到nums[i-1]的和,如此做是为了求sumRange时不需要额外讨论 i == 0的情况。

Time Complexity: NumArray, O(n). sumRange, O(1). n = nums.length.

Space: O(n).

AC Java:

 1 public class NumArray {
 2     private int [] dp;
 3     public NumArray(int[] nums) {
 4         dp = new int[nums.length+1]; //dp[i]表示从nums[0]到nums[i-1]的和
 5         for(int i = 1; i<=nums.length; i++){
 6             dp[i] = dp[i-1] + nums[i-1];
 7         }
 8     }
 9 
10     public int sumRange(int i, int j) {
11         return dp[j+1] - dp[i];
12     }
13 }
14 
15 // Your NumArray object will be instantiated and called as such:
16 // NumArray numArray = new NumArray(nums);
17 // numArray.sumRange(0, 1);
18 // numArray.sumRange(1, 2);

类似Range Sum Query - MutableRange Sum Query 2D - Immutable.

posted @ 2015-11-13 09:32  Dylan_Java_NYC  阅读(315)  评论(0编辑  收藏  举报