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:
- You may assume that the array does not change.
- 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 = 1; i < nums.size(); ++i) { dp[i] += dp[i - 1]; } } int sumRange(int i, int j) { return i == 0? dp[j] : dp[j] - dp[i - 1]; } private: vector<int> dp; };
當然,我們也可以通過增加一位 dp 的長度,來避免在 sumRange 中檢測i是否為0,參見代碼如下:
解法二:
class NumArray { public: NumArray(vector<int> &nums) { dp.resize(nums.size() + 1, 0); for (int i = 1; i <= nums.size(); ++i) { dp[i] = dp[i - 1] + nums[i - 1]; } } int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } private: vector<int> dp; };
類似題目:
Range Sum Query 2D - Immutable
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
