[LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

Given an integer array nums, find the sum of the elements between indices iand 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.

这道题让我们检索一个数组的某个区间的所有数字之和,题目中给了两条条件,首先数组内容不会变化,其次有很多的区间和检索。那么我们用传统的遍历相加来求每次区间和检索,十分的不高效,而且无法通过 OJ。所以这道题的难点就在于是否能想到来用建立累计直方图的思想来建立一个累计和的数组 dp,其中 dp[i] 表示 [0, i] 区间的数字之和,那么 [i,j] 就可以表示为 dp[j]-dp[i-1],这里要注意一下当 i=0 时,直接返回 dp[j] 即可,参见代码如下:

解法一:

class NumArray {
public:
NumArray(vector<int> &nums) {
dp = nums;
for (int i = ; i < nums.size(); ++i) {
dp[i] += dp[i - ];
}
}
int sumRange(int i, int j) {
return i == ? dp[j] : dp[j] - dp[i - ];
}
private:
vector<int> dp;
};

当然,我们也可以通过增加一位 dp 的长度,来避免在 sumRange 中检测i是否为0,参见代码如下:

解法二:

class NumArray {
public:
NumArray(vector<int> &nums) {
dp.resize(nums.size() + , );
for (int i = ; i <= nums.size(); ++i) {
dp[i] = dp[i - ] + nums[i - ];
}
}
int sumRange(int i, int j) {
return dp[j + ] - dp[i];
} private:
vector<int> dp;
};

类似题目:

Range Sum Query 2D - Mutable

Range Sum Query 2D - Immutable

Range Sum Query - Mutable

Maximum Size Subarray Sum Equals k

参考资料:

https://leetcode.com/problems/range-sum-query-immutable/

https://leetcode.com/problems/range-sum-query-immutable/discuss/75184/5-lines-C%2B%2B-4-lines-Python

https://leetcode.com/problems/range-sum-query-immutable/discuss/75192/Java-simple-O(n)-init-and-O(1)-query-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

上一篇:Java自学手记——接口


下一篇:jquery+php实现用户输入搜索内容时自动提示