LeetCode 303. Range Sum Query - Immutable
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 303. 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.
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
思路:
用自底向上的动态规划得到所有sumRange(0, i)的解,保存在public成员solution中;
sumRange(i, j) = sumRange(0, j) - sumRange(0, i - 1);
代码:C++
class NumArray { public: NumArray(vector<int> &nums) { num = nums; if (num.size() > 0) { solution.push_back(num[0]); for (int i = 1; i <= num.size() - 1; i++) { int index = solution[i - 1] + num[i]; solution.push_back(index); } } } int sumRange(int i, int j) { if (i < 0 || j >= num.size()) return 0; if (i == 0) return solution[j]; else return solution[j] - solution[i - 1]; } vector<int> solution; private: vector<int> num; };
以上是关于LeetCode 303. Range Sum Query - Immutable的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 303. Range Sum Query - Immutable
LeetCode_303. Range Sum Query - Immutable
Leetcode 303. Range Sum Query - Immutable
Leetcode 303: Range Sum Query - Immutable