[LeetCode] Range Sum Query - Immutable
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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:
- You may assume that the array does not change.
- There are many calls to sumRange function.
求一个数组的范围和,可以使用动态规划来计算。
dp[x]数组表示原数组nums中前x个元素之和。如果要求nums中i~j内元素和,就要计算dp[j + 1] - dp[i]即可。
class NumArray { public: NumArray(vector<int> nums) : dp(nums.size() + 1, 0) { for (int i = 1; i < dp.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; }; // 29 ms /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
以上是关于[LeetCode] Range Sum Query - Immutable的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 303. Range Sum Query - Immutable
leetcode笔记:Range Sum Query 2D - Immutable
leetcode@ [327] Count of Range Sum (Binary Search)