题目:
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:
链接: http://leetcode.com/problems/range-sum-query-immutable/
题解:
给定数组,求range之内的数组和。 我们可以新建一个dp数组来保存数据,dp[i]表示 0到i-1这i个数的sum,每次我们就可以在使用O(n)初始化之后,用O(1)的时间得到搜索结果了。
Time Complexity - O(n), Space Compleixty - O(1)。
public class NumArray { private int[] sum; public NumArray(int[] nums) { sum = new int[nums.length + 1]; for(int i = 1; i < sum.length; i++) { sum[i] = nums[i - 1] + sum[i - 1] ; } } public int sumRange(int i, int j) { return 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);
Reference:
303. Range Sum Query - Immutable
原文:http://www.cnblogs.com/yrbbest/p/5050025.html