原题链接: https://leetcode.com/problems/range-sum-query-immutable/
Range Sum专题相关题目
303. Range Sum Query - Immutable
304. Range Sum Query 2D - Immutable
1. 题目介绍
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
给出一个整数数组nums,寻找第 i 个元素到第 j 个元素的和。
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.
2. 解题思路
2.1 直接循环累加和
通过循环累加的方式求和。
时间复杂度O(n)。
实现代码
class NumArray {
int [] Array ;
public NumArray(int[] nums) {
int length = nums.length;
Array = new int [length];
for(int i = 0 ;i<length ;i++) {
Array [i] = nums[i];
}
}
public int sumRange(int i, int j) {
int ans = 0;
for(int k = i;k<=j ; k++) {
ans += Array[k];
}
return ans;
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
2.2 动态规划
使用dp数组存储累加和,dp[ i ]存放nums[ 0 ] + nums[ 1 ] +···+nums[ i ]的和。因此 nums[ i ] + nums[ i+1 ] +···+nums[ j ]的和就是dp[ j ]- dp[ i-1 ]
在实际实现中,需要对 i == 0 和nums为空的特殊情况进行处理。
实现代码
class NumArray {
int [] dp = null ;
public NumArray(int[] nums) {
int length = nums.length;
if(length >0) {
dp = new int [ length ];
dp[0] = nums[0];
for(int i = 1 ;i<length ;i++) {
dp [i] = dp[i-1] + nums[i];
}
}
}
public int sumRange(int i, int j) {
if(dp == null) {
return 0;
}
if(i == 0) {
return dp[j];
}
else {
return dp[j]-dp[i-1];
}
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/